package com.motu.monstercity.server.game.logichandler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.redis.RedisKey;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameUnion.*;
import com.motu.monstercity.server.game.base.*;
import com.motu.monstercity.server.game.commondata.act.ActTopRanking;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCardConstant;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.rank.RankReward;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.union.*;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.MotuLogManager;
import com.motu.monstercity.server.game.log.ThinkingDataManager;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.SensitivewordEngine;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.Lock;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class UnionHandler {

    // CMD_GAME_UNION_LIST = 72900; // 获取联盟列表
    public static Object CMD_GAME_UNION_LIST(RequestParam clientParam) throws Exception {
        CSGameUnionListRequest request = CSGameUnionListRequest.parseFrom(clientParam.getData());
        CSGameUnionListResponse.Builder response = CSGameUnionListResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        int serverId = userInfo.getServerId();
        String familyName = request.getUnionName();//目前无需求,用不到
        long unionId = request.getUnionId();
        int index = request.getIndex();
        if (unionId != 0) {
            //通过联盟id 精准搜索
            UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
            // 没有该联盟
            if (unionInfo != null) {
                response.addUnionInfoList(unionInfo.takeBuilder());
            }
        } else {
            //从排行榜获取联盟数据
            int startIndex = index * AllParam.UNION_RANK_LIST_MAX;
            int endIndex = (index + 1) * AllParam.UNION_RANK_LIST_MAX;
            JsonArray unionIdList = RankManager.getRankIdListByIndex(RankConstant.SERVER_RANK_UNION_EARN,serverId,"0",startIndex,endIndex);
            for (int i = 0; i < unionIdList.size(); i++) {
                long unionIdTmp = Long.parseLong(unionIdList.getString(i));
                UnionInfo unionInfo = UnionManager.getUnionInfo(unionIdTmp);
                // 没有该联盟
                if (unionInfo != null) {
                    response.addUnionInfoList(unionInfo.takeInitBuilder());
                }
            }
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        response.setUnionId(userUnion.getUnionId());
        response.setIndex(index);

        return response;
    }

    //CMD_GAME_UNION_CREATE = 72901; // 创建联盟
    public static Object CMD_GAME_UNION_CREATE(RequestParam clientParam) throws Exception {
        CSGameUnionCreateRequest request = CSGameUnionCreateRequest.parseFrom(clientParam.getData());
        CSGameUnionCreateResponse.Builder response = CSGameUnionCreateResponse.newBuilder();
        long userId = clientParam.getUserId();
        String unionName = request.getUnionName();
        String shortName = request.getShortName();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 已有公会
        if (userUnion.getUnionId() != 0) {
            return ErrorWord.ALREADY_MAX;
        }
        // 仍在cd时间
        if (userUnion.isInLeaveCD()) {
            return ErrorWord.STILL_IN_CDTIME;
        }

        ErrorWord checkCode = SensitivewordEngine.checkUserName(unionName);
        if (checkCode != ErrorWord.SUCCESS) {
            return checkCode;

        }
        if (!UnionManager.checkShortName(shortName)) {
            return ErrorWord.INVALID_OPERATION;
        }
//        ErrorWord errorWord = GameManager.checkNickname(familyName, AllParam.FAMILY_NAME_LENGTH[0],
//                AllParam.FAMILY_NAME_LENGTH[1]);
//        if (errorWord != ErrorWord.SUCCESS) {
//            return errorWord;
//        }
        if (Tool.isEmpty(shortName)) {
            return ErrorWord.NOT_DATA_5;
        }
        int icon1 = request.getIcon1();
        int icon2 = request.getIcon2();

        UnionDecorate unionDecorate1 = UnionManager.getUnionDecorate(icon1);
        UnionDecorate unionDecorate2 = UnionManager.getUnionDecorate(icon2);
        if (unionDecorate1 == null || unionDecorate1.getType() != 101) {
            return ErrorWord.NOT_DATA_4;//参数类型错误
        }

        if (unionDecorate2 == null || unionDecorate2.getType() != 201) {
            return ErrorWord.NOT_DATA_4;//参数类型错误
        }
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);


        // 屏蔽# $符号
        unionName = Tool.replaceColorChar(unionName);

        boolean hasEngChar = Tool.checkEngChar(unionName);
        String sql;
        if (hasEngChar)
            sql = "select 1 from union_info where lower(name) = lower(?) and server_id = ? limit 1;";
        else
            sql = "select 1 from union_info where name = ? and server_id = ? limit 1;";
        JsonArray params = new JsonArray();
        params.add(unionName);
        params.add(userInfo.getServerId());
        JsonArray array = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params));
        // 名字已被使用
        if (array != null && array.size() > 0) {
            return ErrorWord.NAME_USED;
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();

        if (userInfo.getVip() >= AllParam.UNION_FREE_CREATE_VIP && userUnion.getIsFreeCreate() == 0) {
            //vip等级达标 可以免费创建一次联盟
            userUnion.putIsFreeCreate(1);
        } else {
            //使用钻石创建联盟
            if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, AllParam.UNION_CREATE_NEED_DIAMOND_NUM)) {
                return ErrorWord.ITEM_LACK;//钻石不足
            }
            RewardManager.subReward(userInfo, ItemId.DIAMOND, AllParam.UNION_CREATE_NEED_DIAMOND_NUM, pbUserData,LogType.UNION_CREATE);
        }

        // 检测敏感字（先进行重名校验，在进行敏感词检测，防止重复刷文字校验api）
        String tempName = unionName;
        try {
            unionName = SensitivewordEngine.replaceNameBySdk(unionName, userExtInfo.getPlatform());
        } catch (Exception e){
            return ErrorWord.BAD_WORD;
        }
        if (!tempName.equals(unionName)) {
            return ErrorWord.BAD_WORD;// 有敏感字
        }

        String tempName2 = shortName;
        try {
            shortName = SensitivewordEngine.replaceNameBySdk(shortName, userExtInfo.getPlatform());
        } catch (Exception e){
            return ErrorWord.BAD_WORD;
        }
        if (!tempName2.equals(shortName)) {
            return ErrorWord.BAD_WORD;// 有敏感字
        }

        // 创建公会成和创建成员对象
        UnionInfo unionInfo = new UnionInfo(unionName, userId, userInfo.getUserName(), userInfo.getServerId(),icon1,icon2);
        unionInfo.putShortName(shortName);
        int limitType = request.getLimitType();//是否开启审批
        unionInfo.putLimitType(limitType);
        unionInfo.doCreate();

        //默认创建联盟总部 等级为1
        long curTime = TimeUtils.getCurTime();
        UnionBuild unionBuild = new UnionBuild(unionInfo.getId(),UnionBuildMain.BUILD_ID_MAIN);
        unionBuild.putStartTime(curTime);
        unionBuild.putBuildTime(curTime);
        unionBuild.putLevel(1);
        unionBuild.doCreate();
        ProtoDataUtils.updatePBUserData(pbUserData, unionBuild);

        // 创建联盟宝箱
        UnionBoxInfo unionBoxInfo = new UnionBoxInfo(unionInfo.getId(), unionInfo.getLevel());
        unionBoxInfo.insert();

        userUnion.putPost(UnionManager.POST_TYPE_MASTER);
        userUnion.joinUnion(userId,unionInfo, userInfo, pbUserData);

        //下发数据
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        ProtoDataUtils.updatePBUserData(pbUserData, UnionManager.takeUserUnionMemberBuilder(userUnion));

        GameUser.sendRedPointPrompt(userInfo, userExtInfo, SystemConstant.RED_POINT_UNION);

        return response;
    }


    // CMD_GAME_UNION_CHANGE_NAME = 72902; // 联盟改名
    public static Object CMD_GAME_UNION_CHANGE_NAME(RequestParam clientParam) throws Exception {
        CSGameUnionChangeNameRequest request = CSGameUnionChangeNameRequest.parseFrom(clientParam.getData());
        CSGameUnionChangeNameResponse.Builder response = CSGameUnionChangeNameResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        String newUnionName = request.getNewName();
        String newShortName = request.getNewShortName();
        if (Tool.isEmpty(newUnionName) && Tool.isEmpty(newShortName)) {
            return ErrorWord.BAD_PARAM;
        }

        //使用钻石修改名字
        if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, AllParam.UNION_CHANGE_NAME_NEED_DIAMOND_NUM)) {
            return ErrorWord.ITEM_LACK;//钻石不足
        }

        //名字不为空且不与原来的名字一致情况下才处理
        if (!Tool.isEmpty(newUnionName) && !unionInfo.getName().equals(newUnionName)) {
            // 屏蔽# $符号
            newUnionName = Tool.replaceColorChar(newUnionName);

            boolean hasEngChar = Tool.checkEngChar(newUnionName);
            String sql;
            if (hasEngChar)
                sql = "select 1 from union_info where lower(name) = lower(?) and server_id = ? limit 1;";
            else
                sql = "select 1 from union_info where name = ? and server_id = ? limit 1;";
            JsonArray params = new JsonArray();
            params.add(newUnionName);
            params.add(userInfo.getServerId());
            JsonArray array = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params));
            // 名字已被使用
            if (array != null && array.size() > 0) {
                return ErrorWord.NAME_USED;
            }

            // 检测敏感字（先进行重名校验，在进行敏感词检测，防止重复刷文字校验api）
            String tempName = newUnionName;
            try {
                newUnionName = SensitivewordEngine.replaceNameBySdk(newUnionName, userExtInfo.getPlatform());
            } catch (Exception e){
                return ErrorWord.BAD_WORD;
            }
            if (!tempName.equals(newUnionName)) {
                return ErrorWord.BAD_WORD;// 有敏感字
            }


            unionInfo.putName(newUnionName);
        }

        //简称不为空且不与原来的名字一致情况下才处理
        if (!Tool.isEmpty(newShortName) && !unionInfo.getName().equals(newShortName)) {
            if (!UnionManager.checkShortName(newShortName)) {
                return ErrorWord.INVALID_OPERATION;
            }

            // 检测敏感字（先进行重名校验，在进行敏感词检测，防止重复刷文字校验api）
            String tempName2 = newShortName;
            try {
                newShortName = SensitivewordEngine.replaceNameBySdk(newShortName, userExtInfo.getPlatform());
            } catch (Exception e){
                return ErrorWord.BAD_WORD;
            }
            if (!tempName2.equals(newShortName)) {
                return ErrorWord.BAD_WORD;// 有敏感字
            }

            unionInfo.putShortName(newShortName);
        }
        unionInfo.update();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
//        if (unionInfo.getIsRenameFree() == 0) {
//            //首次免费改名
//            unionInfo.putIsRenameFree((byte) 1);
//        } else {
//
//        }

        RewardManager.subReward(userInfo, ItemId.DIAMOND, AllParam.UNION_CHANGE_NAME_NEED_DIAMOND_NUM, pbUserData,LogType.UNION_CHANGE_NAME);
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        return response;
    }

    // CMD_GAME_UNION_CHANGE_ICON = 72903; // 联盟改头像
    public static Object CMD_GAME_UNION_CHANGE_ICON(RequestParam clientParam) throws Exception {
        CSGameUnionChangeIconRequest request = CSGameUnionChangeIconRequest.parseFrom(clientParam.getData());
        CSGameUnionChangeIconResponse.Builder response = CSGameUnionChangeIconResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        int newIcon1 = request.getIcon1();
        int newIcon2 = request.getIcon2();

        UnionDecorate unionDecorate1 = UnionManager.getUnionDecorate(newIcon1);
        UnionDecorate unionDecorate2 = UnionManager.getUnionDecorate(newIcon2);
        if (unionDecorate1 == null || unionDecorate1.getType() != 101) {
            return ErrorWord.BAD_PARAM;//参数类型错误
        }

        if (unionDecorate2 == null || unionDecorate2.getType() != 201) {
            return ErrorWord.BAD_PARAM;//参数类型错误
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
//        if (unionInfo.getIsReiconFree() == 0) {
//            //首次免费改头像
//            unionInfo.putIsReiconFree((byte) 1);
//        } else {
//
//        }
        //使用钻石改头像
        if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, AllParam.UNION_CHANGE_ICON_NEED_DIAMOND_NUM)) {
            return ErrorWord.ITEM_LACK;//钻石不足
        }
        RewardManager.subReward(userInfo, ItemId.DIAMOND, AllParam.UNION_CHANGE_ICON_NEED_DIAMOND_NUM, pbUserData,LogType.UNION_CHANGE_ICON);
        unionInfo.putIcon(newIcon1 + "-" + newIcon2);
        unionInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        return response;
    }

    // CMD_GAME_UNION_CHANGE_LIMIT = 72904; // 联盟改入会限制
    public static Object CMD_GAME_UNION_CHANGE_LIMIT(RequestParam clientParam) throws Exception {
        CSGameUnionChangeLimitRequest request = CSGameUnionChangeLimitRequest.parseFrom(clientParam.getData());
        CSGameUnionChangeLimitResponse.Builder response = CSGameUnionChangeLimitResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        int limitType = request.getLimitType();
        int limitLevel = request.getLimitLevel();
        int limitLevelOpen = request.getLimitLevelOpen();
        if (limitType != 0 && limitType != 1) {
            return ErrorWord.BAD_PARAM;
        }
        if(!Tool.isInList(AllParam.UNION_LIMIT_LEVEL,limitLevel)){
            return ErrorWord.BAD_PARAM;
        }
        if (limitLevelOpen != 0 && limitLevelOpen != 1) {
            return ErrorWord.BAD_PARAM;
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        unionInfo.putLimitType(limitType);
        unionInfo.putLimitLevel(limitLevel);
        unionInfo.putLimitLevelOpen(limitLevelOpen);
        unionInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        return response;
    }



    // CMD_GAME_UNION_CHANGE_NOTICE = 72905; // 联盟改公告
    public static Object CMD_GAME_UNION_CHANGE_NOTICE(RequestParam clientParam) throws Exception {
        CSGameUnionChangeNoticeRequest request = CSGameUnionChangeNoticeRequest.parseFrom(clientParam.getData());
        CSGameUnionChangeNoticeResponse.Builder response = CSGameUnionChangeNoticeResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionInfoLock(unionId));
            UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
            //公告检验
            String newNotice = request.getNotice();
            // 过滤敏感字符
            // 过滤敏感字符
            try {
                newNotice = SensitivewordEngine.replaceWordBySdk(newNotice, userExtInfo.getPlatform());
            } catch (Exception e) {
                return ErrorWord.BAD_WORD;
            }


            if (newNotice.length() > AllParam.UNION_NOTICE_MAX) {
                newNotice = newNotice.substring(0, AllParam.UNION_NOTICE_MAX);
            }
            unionInfo.putNotice(newNotice);
            unionInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
            UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_NOTICE, userInfo.getUserName());
        } catch (Exception e) {
            MainService.logger.error("changeUnionNotice userId :" +userId+" error :" + Tool.getException(e));
            return ErrorWord.LOGIC_EXCEPTION;
        } finally {
            MainService.releaseVertLock(lock);
        }
        return response;
    }

    // CMD_GAME_UNION_DONATE_INFO = 72906; // 联盟捐献初始化
    public static Object CMD_GAME_UNION_DONATE_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionDonateInfoRequest request = CSGameUnionDonateInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionDonateInfoResponse.Builder response = CSGameUnionDonateInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UnionDonateInfo unionDonateInfo = UnionManager.getUnionDonateInfo(unionInfo.getId());
        if (unionDonateInfo != null ) {
            ProtoDataUtils.updatePBUserData(pbUserData, unionDonateInfo,true);
        }
        return response;
    }

    // CMD_GAME_UNION_APPLY = 72907; // 申请进入联盟
    public static Object CMD_GAME_UNION_APPLY(RequestParam clientParam) throws Exception {
        CSGameUnionApplyRequest request = CSGameUnionApplyRequest.parseFrom(clientParam.getData());
        CSGameUnionApplyResponse.Builder response = CSGameUnionApplyResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 已加入联盟
        if (userUnion.getUnionId() != 0) {
            return ErrorWord.NOT_DATA_1;
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        int isRadomJoin = request.getIsRandomJoin();
        if (isRadomJoin == 1) {
            //随机加入
            //从数据库中随机搜索一条不用审批 未满员的联盟
            int num = 14;//1级联盟14人 每升1级增加1人
            int serverId = userInfo.getServerId();
            String randomUnionSql = "SELECT id FROM union_info  where  member_num < level+"+num+" and server_id = ? and limit_type = 0 ORDER BY RAND() LIMIT 1;";
            JsonArray params = new JsonArray();
            params.add(serverId);
            JsonObject randomUnion = Future.await(MysqlTool.queryJsonObjectFromDb(MysqlClient.getGamePool(), randomUnionSql,params ));
            if (randomUnion == null) {
                return ErrorWord.NOT_DATA;//没有可加入的随机联盟
            }
            long unionId = randomUnion.getLong("id");

            Lock lock = null;
            try {
                lock = MainService.getVertLock(LockKey.getUnionInfoLock(unionId));
                UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
                UnionMain unionMain = UnionManager.getUnionMain(unionInfo.getLevel());
                int memberNum = UnionManager.getUnionMemberNum(unionId);
                //公会成员人数已满
                if (unionMain != null && memberNum >= unionMain.getNum()) {
                    return ErrorWord.WRONG_STATUS;
                }
                // 无需申请，直接加入公会
                userUnion.putPost(UnionManager.POST_TYPE_COMMON);
                userUnion.joinUnion(userId,unionInfo, userInfo, pbUserData);
                ProtoDataUtils.updatePBUserData(pbUserData, unionInfo,true);
                // 创建公会成员对象
                UnionMember unionMember = new UnionMember(unionId, userId);
                unionMember.doCreate();

                // 删除该玩家的其他申请
                UnionManager.deleteAllUserApply(userId);
                response.setIsJoin(true);

                ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
                //创建联盟动态
                UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_JOIN, userInfo.getUserName());

                GameUser.sendRedPointPrompt(userInfo, userExtInfo, SystemConstant.RED_POINT_UNION);

            } catch (Exception e) {
                throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);

            } finally {
                MainService.releaseVertLock(lock);
            }
        } else {
            long unionId = request.getUnionId();
            UnionUserApply unionUserApply = UnionManager.getUnionUserApply(unionId, userId);
            // 已提交申请
            if (unionUserApply != null) {
                return ErrorWord.ALREADY_MAX;
            }

            Lock lock = null;
            try {
                lock = MainService.getVertLock(LockKey.getUnionInfoLock(unionId));
                UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
                // 不能加入本服之外该公会
                if (userInfo.getServerId() != unionInfo.getServerId()) {
                    return ErrorWord.NOT_DATA_7;
                }
                if (unionInfo.getLimitType() == UnionInfo.FAMILY_LIMIT0) {
                    UnionMain unionMain = UnionManager.getUnionMain(unionInfo.getLevel());
                    int memberNum = UnionManager.getUnionMemberNum(unionId);
                    //公会成员人数已满
                    if (unionMain != null && memberNum >= unionMain.getNum()) {
                        return ErrorWord.WRONG_STATUS;
                    }
                    // 无需申请，直接加入公会
                    userUnion.putPost(UnionManager.POST_TYPE_COMMON);
                    userUnion.joinUnion(userId,unionInfo, userInfo, pbUserData);
                    // 创建公会成员对象
                    UnionMember unionMember = new UnionMember(unionInfo.getId(), userId);
                    unionMember.doCreate();

                    // 删除该玩家的其他申请
                    UnionManager.deleteAllUserApply(userId);
                    response.setIsJoin(true);
                    ProtoDataUtils.updatePBUserData(pbUserData, unionInfo,true);
                    ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
                    //创建联盟动态
                    UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_JOIN, userInfo.getUserName());

                    GameUser.sendRedPointPrompt(userInfo, userExtInfo, SystemConstant.RED_POINT_UNION);

                } else {
                    if (unionInfo.getLimitLevelOpen() == 1 && userInfo.getLevel() < unionInfo.getLimitLevel()) {
                        return ErrorWord.LEVEL_LACK;//申请等级不够
                    }
                    // 提交申请
                    unionUserApply = new UnionUserApply(unionId, userId);
                    unionUserApply.doCreate();
                    UserUnionApply userUnionApply = UnionManager.getUserUnionApply(userId, unionId);
                    if (userUnionApply == null) {
                        userUnionApply = new UserUnionApply(userId, unionId);
                        userUnionApply.doCreate();
                    }
                    response.setIsJoin(false);
                    response.setUnionId(unionId);
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);
            } finally {
                MainService.releaseVertLock(lock);
            }
        }
        return response;
    }

    // CMD_GAME_UNION_APPLY_LIST = 72908; // 联盟申请列表
    public static Object CMD_GAME_UNION_APPLY_LIST(RequestParam clientParam) throws Exception {
        CSGameUnionApplyListRequest request = CSGameUnionApplyListRequest.parseFrom(clientParam.getData());
        CSGameUnionApplyListResponse.Builder response = CSGameUnionApplyListResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        List<UnionUserApply> unionUserApplyList = UnionManager.getUnionUserApplyList(userUnion.getUnionId());
        for (UnionUserApply unionUserApply : unionUserApplyList) {
            response.addUnionApplylist(UnionManager.takeUserUnionMemberBuilder(unionUserApply.getUserId()));
        }

        return response;
    }

    // CMD_GAME_UNION_APPLY_OPERATE = 72909; // 操作申请
    public static Object CMD_GAME_UNION_APPLY_OPERATE(RequestParam clientParam) throws Exception {
        CSGameUnionApplyOperateRequest request = CSGameUnionApplyOperateRequest.parseFrom(clientParam.getData());
        CSGameUnionApplyOperateResponse.Builder response = CSGameUnionApplyOperateResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        long unionId = userUnion.getUnionId();
        List<Long> userIdListList = request.getUserIdListList();
        boolean isAgree = request.getIsAgree();
        for (int i = 0; i < userIdListList.size(); i++) {
            long taggedUserId = userIdListList.get(i);
            Common.PBUserData.Builder pbUserData = response.getUserBuilder();

            if (isAgree) {
                UnionMain unionMain = UnionManager.getUnionMain(unionInfo.getLevel());
                int memberNum = UnionManager.getUnionMemberNum(unionId);
                //公会成员人数已满
                if (unionMain != null && memberNum >= unionMain.getNum()) {
                    return ErrorWord.ALREADY_MAX;
                }
                UserUnion userUnionTarget = UnionManager.getUserUnion(taggedUserId);
                if (userUnionTarget.getUnionId() != 0) {
                    return ErrorWord.WRONG_STATUS;
                }
                UserInfo userInfoTarget = GameUser.getUserInfo(taggedUserId);
                userUnionTarget.putPost(UnionManager.POST_TYPE_COMMON);
                userUnionTarget.joinUnion(userId,unionInfo,userInfoTarget , null);
                // 创建公会成员对象
                UnionMember unionMember = new UnionMember(unionInfo.getId(), taggedUserId);
                unionMember.doCreate();
                // 删除该玩家的其他申请
                UnionManager.deleteAllUserApply(taggedUserId);
                ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
                ProtoDataUtils.updatePBUserData(pbUserData, unionMember);
                //创建联盟动态
                UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_JOIN, userInfoTarget.getUserName());
            } else {
                // 删除该玩家的申请
                UnionManager.deleteUserAndUnionApply(taggedUserId,unionId,null,null);
            }
        }
        response.setIsAgree(isAgree);
        response.addAllUserIdList(userIdListList);
        return response;
    }

    // CMD_GAME_UNION_APPOINT = 72910; // 任命职务
    public static Object CMD_GAME_UNION_APPOINT(RequestParam clientParam) throws Exception {
        CSGameUnionAppointRequest request = CSGameUnionAppointRequest.parseFrom(clientParam.getData());
        CSGameUnionAppointResponse.Builder response = CSGameUnionAppointResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        Long targetId = request.getUserId();
        int post = request.getPost();
        // 不能任命自己
        if (userId == targetId) {
            return ErrorWord.MYSELF;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足--盟主和副盟主才可以任命职位
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }
        // 权限不足--副盟主以上的职位只有盟主可操作
        if ((post == UnionManager.POST_TYPE_MASTER || post == UnionManager.POST_TYPE_DEPUTY) && !userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        // 权限不足--精英 副盟主以上的职位都可操作
        if (post == UnionManager.POST_TYPE_ELITE && !userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null){
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        UserUnion userUnionTarget = UnionManager.getUserUnion(targetId);
        //不是同一个联盟
        if (userUnionTarget == null || userUnionTarget.getUnionId() != unionId) {
            return ErrorWord.WRONG_STATUS;
        }
//        // 实习期不能被任命
//        if (userUnionTarget.isInTemp()) {
//            return  ErrorWord.NOT_DATA_6;
//        }
        // 职位相同
        if (userUnionTarget.getPost() == post) {
            return ErrorWord.NOT_DATA_7;
        }
        int postNum = UnionManager.getPostNum(unionId, post);
        UnionMain unionMain = UnionManager.getUnionMain(unionInfo.getLevel());
        // 职位人数已满
        if ((post == UnionManager.POST_TYPE_DEPUTY && postNum >= unionMain.getDeputy()) ||
                (post == UnionManager.POST_TYPE_ELITE && postNum >= unionMain.getElite())) {
            return ErrorWord.NOT_DATA_8;
        }

        userUnionTarget.putPost(post);
        userUnionTarget.updateQueueNow();
        UserInfo targetUserInfo = GameUser.getUserInfo(targetId);

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        // 更换会长
        if (post == UnionManager.POST_TYPE_MASTER) {
            userUnion.putPost(UnionManager.POST_TYPE_COMMON);
            userUnion.update();
            unionInfo.putMasterId(targetId);
            unionInfo.putMasterName(targetUserInfo.getUserName());
            unionInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
            ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
            ProtoDataUtils.updatePBUserData(pbUserData, UnionManager.takeUserUnionMemberBuilder(userUnion));
        }
        ProtoDataUtils.updatePBUserData(pbUserData, UnionManager.takeUserUnionMemberBuilder(userUnionTarget));

        //创建联盟动态
        int msgPostionId = 0;
        if(post == UnionManager.POST_TYPE_DEPUTY){
            msgPostionId =MailConstant.UNION_DYNAMIC_POSTION_1;
        } else if (post == UnionManager.POST_TYPE_ELITE) {
            msgPostionId =MailConstant.UNION_DYNAMIC_POSTION_2;
        } else if (post == UnionManager.POST_TYPE_COMMON) {
            msgPostionId =MailConstant.UNION_DYNAMIC_POSTION_3;
        }
        UnionManager.addUnionDynamicRecord(unionId, msgPostionId,targetUserInfo.getUserName(), userInfo.getUserName());
        return response;
    }

    // CMD_GAME_UNION_EXIT = 72911; // 退出联盟
    public static Object CMD_GAME_UNION_EXIT(RequestParam clientParam) throws Exception {
        CSGameUnionExitRequest request = CSGameUnionExitRequest.parseFrom(clientParam.getData());
        CSGameUnionExitResponse.Builder response = CSGameUnionExitResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        if (RankActManager.hasUnionRank(userInfo)) {
            return ErrorWord.INVALID_OPERATION; // 联盟冲榜期间不能退出联盟
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        // 会长不能退出公会
        if (userUnion.getPost() == UnionManager.POST_TYPE_MASTER) {
            return ErrorWord.NOT_DATA_2;
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();

        userUnion.exitUnion(userId,unionInfo,userInfo,pbUserData,true,true);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);

        //创建联盟动态
        UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_EXIT, userInfo.getUserName());


        return response;
    }

    // CMD_GAME_UNION_KICK = 72912; // 踢出联盟
    public static Object CMD_GAME_UNION_KICK(RequestParam clientParam) throws Exception {
        CSGameUnionKickRequest request = CSGameUnionKickRequest.parseFrom(clientParam.getData());
        CSGameUnionKickResponse.Builder response = CSGameUnionKickResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        long targetId = request.getUserId();
        UserUnion userUnionTarget = UnionManager.getUserUnion(targetId);
        UserInfo userInfoTarget = GameUser.getUserInfo(targetId);
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        userUnionTarget.exitUnion(userId,unionInfo,userInfoTarget,null,false,true);
        ProtoDataUtils.deletePBUserData(pbUserData, userUnionTarget);

        //创建联盟动态
        UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_EXIT, userInfoTarget.getUserName());
        return response;
    }

    // CMD_GAME_UNION_DYNAMIC_LIST = 72913; // 联盟动态列表
    public static Object CMD_GAME_UNION_DYNAMIC_LIST(RequestParam clientParam) throws Exception {
        CSGameUnionDynamicListRequest request = CSGameUnionDynamicListRequest.parseFrom(clientParam.getData());
        CSGameUnionDynamicListResponse.Builder response = CSGameUnionDynamicListResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        List<UnionDynamicRecord> list = UnionManager.getUnionDynamicRecordList(unionId);
        for (UnionDynamicRecord unionDynamicRecord : list){
            response.addList(unionDynamicRecord.takeBuilder(userInfo.getLanguage()));
        }
        return response;
    }



    //CMD_GAME_UNION_RANK = 72914; // 联盟排行榜(搜索联盟)
    public static Object CMD_GAME_UNION_RANK(RequestParam clientParam) throws Exception {
        CSGameUnionRankRequest request = CSGameUnionRankRequest.parseFrom(clientParam.getData());
        CSGameUnionRankResponse.Builder response = CSGameUnionRankResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        int serverId = userInfo.getServerId();
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        String rankName = RankManager.getRankName(RankConstant.SERVER_RANK_UNION_EARN,serverId, 0);
        long targaUnionId = request.getKey();
        if (targaUnionId != 0) {
            UnionInfo unionInfo = UnionManager.getUnionInfo(targaUnionId);
            if (unionInfo != null) {
                response.addUnionInfoList(unionInfo.takeBuilder());
            }
            Long myRank = Future.await(RedisTools.getMyRank(rankName, targaUnionId + ""));
            response.setSearchRankIndex(Math.toIntExact(myRank));
        } else {
            boolean withScore = true;// 带分数返回的是[id1,score1,id2,score2]）
            JsonArray list = Future.await(RedisTools.getRankListByIndex(rankName, 0, 100, withScore));
            for (int i = 0; i < list.size(); i++) {
                if (i % 2 == 0) {// userid
                    String uidStr = list.getString(i);
                    long unionId = Long.parseLong(uidStr);// 用户id
                    double score = Double.parseDouble(list.getString(i + 1));
                    UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
                    if (unionInfo != null) {
                        response.addUnionInfoList(unionInfo.takeBuilder());
                    } else {
                        RedisTools.removeFromRank(rankName, unionId);//排行榜上联盟不存在的话 移除该联盟
                    }
                }
            }
        }

        return response;
    }
    // CMD_GAME_UNION_INFO = 72915; // 联盟信息
    public static Object CMD_GAME_UNION_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionInfoRequest request = CSGameUnionInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionInfoResponse.Builder response = CSGameUnionInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        long unionId = request.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        if (unionInfo == null) {
            return ErrorWord.INVALID_OPERATION;
        }
        response.setUnionInfo(unionInfo.takeBuilder());
        List<Common.PBUserUnionMember> pbUnionMemberList = UnionManager.sortUnionMemberList(unionId);
        for (Common.PBUserUnionMember pbUnionMember : pbUnionMemberList){
            response.putUserUnionMemberList(pbUnionMember.getUserId(),pbUnionMember);
        }
        return response;
    }

    //CMD_GAME_UNION_DONATE = 72916; // 联盟捐献
    public static Object CMD_GAME_UNION_DONATE(RequestParam clientParam) throws Exception {
        CSGameUnionDonateRequest request = CSGameUnionDonateRequest.parseFrom(clientParam.getData());
        CSGameUnionDonateResponse.Builder response = CSGameUnionDonateResponse.newBuilder();
        long userId = clientParam.getUserId();
        int type = request.getType();
        UnionDonateMain unionDonateMain = UnionManager.getUnionDonateMain(type);
        if (unionDonateMain == null) {
            return ErrorWord.BAD_PARAM;
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        long unionId = userUnion.getUnionId();
        JsonObject userDonateJson = userUnion.getUserDonateJson();
        int donateNum = userDonateJson.containsKey(String.valueOf(type)) ? userDonateJson.getInteger(String.valueOf(type)) : 0;
        if (donateNum >= unionDonateMain.getNum()) {
            return ErrorWord.ALREADY_MAX;//捐献次数已达上限
        }
        boolean isFree = false;
        if(type == UnionDonateMain.TYPE_2){
            //中级捐献需要判断特权卡-远征互助卡的权益
            isFree = IapManager.takePrivilegeValueByType(userId, PrivilegeCardConstant.TYPE_IS_GUILD_BUILD_1) > 0 ? true : false;// 购买的特权卡是否有中级捐献免费次数

        } else if(type == UnionDonateMain.TYPE_3){
            //高级捐献需要判断特权卡-终身卡的权益
            isFree = IapManager.takePrivilegeValueByType(userId, PrivilegeCardConstant.TYPE_IS_GUILD_BUILD_2) > 0 ? true : false;// 购买的特权卡是否有高级捐献免费次数
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        if (!isFree) {
            if (!BagManager.checkNeedItemNum(userInfo, unionDonateMain.getNeedItemList())) {
                return ErrorWord.ITEM_LACK;//消耗道具不足
            }
            RewardManager.subReward(userInfo, unionDonateMain.getNeedItemList(), pbUserData,LogType.UNION_DONATE,type);
        }

        userDonateJson.put(String.valueOf(type),donateNum + 1);
        userUnion.putDonateNum(userDonateJson.toString());
        userUnion.update();

        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionInfoLock(unionId));
            UnionDonateInfo unionDonateInfo = UnionManager.getUnionDonateInfo(unionId);
            if (unionDonateInfo == null) {
                unionDonateInfo = new UnionDonateInfo(unionId);
                unionDonateInfo.doCreate();
            } else {
                unionDonateInfo.addProgress(1);//增加联盟贡献进度
                unionDonateInfo.update();
            }
            unionInfo.addExp(unionDonateMain.getExp());
            unionInfo.update();
            RewardManager.addReward(userInfo, unionDonateMain.getRewardItemList(), pbUserData,LogType.UNION_DONATE,type);
            ProtoDataUtils.updatePBUserData(pbUserData, unionDonateInfo);

        } catch (Exception e) {
            throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);
        } finally {
            MainService.releaseVertLock(lock);
        }

        userUnion = UnionManager.getUserUnion(userId);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion,true);
        unionInfo = UnionManager.getUnionInfo(unionId);
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo,true);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_33, 1);// 联盟捐赠{0}次
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_163, 1);// 联盟累计建设{0}次
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_33, 1);
        RankActManager.addUnionRank(userInfo, ActTopRanking.RANK_TYPE_UNION_EXP, unionInfo.getExp(), false);
        RankActManager.addUnionCrossRank(userInfo, ActTopRanking.RANK_TYPE_UNION_EXP, unionInfo.getExp(), false);

        //创建联盟动态
        int msgDonateId = 0;
        if(type == UnionDonateMain.TYPE_1){
             msgDonateId =MailConstant.UNION_DYNAMIC_DONATE_1;
        } else if (type == UnionDonateMain.TYPE_2) {
            msgDonateId =MailConstant.UNION_DYNAMIC_DONATE_2;
        } else if (type == UnionDonateMain.TYPE_3) {
            msgDonateId =MailConstant.UNION_DYNAMIC_DONATE_3;
        } else if (type == UnionDonateMain.TYPE_4) {
            msgDonateId =MailConstant.UNION_DYNAMIC_DONATE_4;
        }
        UnionManager.addUnionDynamicRecord(unionId, msgDonateId, userInfo.getUserName());

        ThinkingDataManager.pushUserUnionDonateEvent(userInfo, type);// 上报数数
        return response;
    }

    //CMD_GAME_UNION_DONATE_REWARD = 72917; // 联盟捐献领奖
    public static Object CMD_GAME_UNION_DONATE_REWARD(RequestParam clientParam) throws Exception {
        CSGameUnionDonateRewardRequest request = CSGameUnionDonateRewardRequest.parseFrom(clientParam.getData());
        CSGameUnionDonateRewardResponse.Builder response = CSGameUnionDonateRewardResponse.newBuilder();
        int progress = request.getProgrss();
        UnionDonateDay unionDonateDay = UnionManager.getUnionDonateDay(progress);
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        List<Integer> userDonateProgressRewardList = userUnion.getUserDonateProgressReward();
        if (userDonateProgressRewardList.indexOf(progress) != -1) {
            return ErrorWord.ALREADY_MAX;//已经领取过
        }
        UnionDonateInfo unionDonateInfo = UnionManager.getUnionDonateInfo(unionInfo.getId());
        if (unionDonateInfo == null || unionDonateInfo.getProgress() < unionDonateDay.getNum()) {
            return ErrorWord.INVALID_OPERATION;//贡献进度不足
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        userDonateProgressRewardList.add(progress);
        String userDonateProgressRewardStr = userDonateProgressRewardList.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(";"));
        userUnion.putDonateProgressReward(userDonateProgressRewardStr);
        userUnion.update();
        RewardManager.addReward(userInfo, unionDonateDay.getRewardItemList(), pbUserData,LogType.UNION_DONATE_PROGRESS,progress);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        return response;
    }


    //CMD_GAME_UNION_INFO_INIT = 72918; // 联盟信息初始化
    public static Object CMD_GAME_UNION_INFO_INIT(RequestParam clientParam) throws Exception {
        CSGameUnionInfoInitRequest request = CSGameUnionInfoInitRequest.parseFrom(clientParam.getData());
        CSGameUnionInfoInitResponse.Builder response = CSGameUnionInfoInitResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        int serverId = userInfo.getServerId();
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            // 没有加入联盟-下发前五联盟的排行信息
            String rankName = RankManager.getRankName(RankConstant.SERVER_RANK_UNION_EARN,serverId, 0);
            boolean withScore = true;// 带分数返回的是[id1,score1,id2,score2]）
            JsonArray list = Future.await(RedisTools.getRankListByIndex(rankName, 0, 5, withScore));
            for (int i = 0; i < list.size(); i++) {
                if (i % 2 == 0) {// userid
                    String uidStr = list.getString(i);
                    long unionId = Long.parseLong(uidStr);// 用户id
                    double score = Double.parseDouble(list.getString(i + 1));
                    UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
                    if (unionInfo != null) {
                        response.addUnionInfoList(unionInfo.takeInitBuilder());
                    }
                }
            }
            Common.PBUnionInfoData.Builder pbUnionInfoData = Common.PBUnionInfoData.newBuilder();
            pbUnionInfoData.setUserUnion(userUnion.takeInitBuilder());
            response.getUserBuilder().setUnion(pbUnionInfoData);
        } else {
            long unionId = userUnion.getUnionId();
            UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
            // 没有该联盟
            if (unionInfo == null) {
                return ErrorWord.ENTITY_NOT_EXIST;
            }
            Common.PBUserData.Builder pbUserData = response.getUserBuilder();
            ProtoDataUtils.updatePBUserData(pbUserData, unionInfo,true);//下发联盟信息
            ProtoDataUtils.updatePBUserData(pbUserData, userUnion,true);//下发玩家联盟个人信息
            List<UnionBuild> unionBuildList = UnionManager.getUnionBuildList(unionInfo.getId());
            for (UnionBuild unionBuild : unionBuildList) {
                ProtoDataUtils.updatePBUserData(pbUserData, unionBuild,true);//下发建筑信息
            }
            //下发成员信息
            List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
            for (UnionMember unionMember : unionMemberList) {
                UserUnion userUnionMember = UnionManager.getUserUnion(unionMember.getUserId());
                ProtoDataUtils.updatePBUserData(pbUserData, UnionManager.takeUserUnionMemberBuilder(userUnionMember));
            }

        }
        return response;
    }

    // CMD_GAME_UNION_DISSOLVE = 72919; // 解散联盟
    public static Object CMD_GAME_UNION_DISSOLVE(RequestParam clientParam) throws Exception {
        CSGameUnionDissolveRequest request = CSGameUnionDissolveRequest.parseFrom(clientParam.getData());
        CSGameUnionDissolveResponse.Builder response = CSGameUnionDissolveResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        if (RankActManager.hasUnionRank(userInfo)) {
            return ErrorWord.INVALID_OPERATION; // 联盟冲榜期间不能退出联盟
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostMaster()) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        long unionId = userUnion.getUnionId();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionInfoLock(unionId));

            // 删除公会成员数据并通知
            List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
            for (UnionMember unionMember : unionMemberList) {
                try {
                    Common.PBUserData.Builder pbMemberUserData = null;
                    UserUnion userUnionMember = null;
                    if(unionMember.getUserId() == userId){
                        userUnionMember = userUnion;
                        pbMemberUserData = pbUserData;
                    } else {
                        userUnionMember = UnionManager.getUserUnion(unionMember.getUserId());
                    }
                    if (userUnionMember == null) {
                        continue;
                    }
                    UserInfo userInfoMember = GameUser.getUserInfo(unionMember.getUserId());
                    if (userInfoMember == null) {
                        continue;
                    }
                    userUnionMember.exitUnion(userId,unionInfo,userInfoMember,pbMemberUserData,false,false);

                } catch (Exception e) {
                    String errMsg = Tool.getException(e);
                    MainService.logger.error(errMsg);
                }
            }
            unionInfo.delete();
            RankManager.removeFromRank(RankConstant.SERVER_RANK_UNION_EARN,userInfo.getServerId(), unionId, "0");
            // 删除公会动态
//        UnionManager.deleteUnionDynamic(familyId);
            // 删除公会申请
            UnionManager.deleteAllUnionApply(unionId);
        } catch (Exception e) {
            throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);

        } finally {
            MainService.releaseVertLock(lock);
        }

        ProtoDataUtils.deletePBUserData(pbUserData, unionInfo);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion,true);
        return response;
    }

    //CMD_GAME_UNION_MEMBER_INFO = 72920; // 获取成员列表
    public static Object CMD_GAME_UNION_MEMBER_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionMemberInfoRequest request = CSGameUnionMemberInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionMemberInfoResponse.Builder response = CSGameUnionMemberInfoResponse.newBuilder();

        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();

        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<Common.PBUserUnionMember> pbUnionMemberList = UnionManager.sortUnionMemberList(unionId);
        for (Common.PBUserUnionMember pbUnionMember : pbUnionMemberList){
            pbUserData.getUnionBuilder().putUserUnionMemberList(pbUnionMember.getUserId(),pbUnionMember);
        }
        return response;
    }


    // CMD_GAME_UNION_CHANGE_TAG = 72921; // 联盟修改标签
    public static Object CMD_GAME_UNION_CHANGE_TAG(RequestParam clientParam) throws Exception {
        CSGameUnionChangeTagRequest request = CSGameUnionChangeTagRequest.parseFrom(clientParam.getData());
        CSGameUnionChangeTagResponse.Builder response = CSGameUnionChangeTagResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        //标签检验
        String tagList = request.getTagList();
        if (!Tool.isEmpty(tagList)) {
            String[] tagArray = tagList.split(";");
            for (int i = 0; i < tagArray.length; i++) {
                int tagId = Integer.parseInt(tagArray[i]);
                UnionTag unionTag = UnionManager.getUnionTag(tagId);
                if (unionTag == null){
                    return ErrorWord.BAD_PARAM;
                }
            }
        } else {
            tagList = "";
        }
        unionInfo.putTagList(tagList);
        unionInfo.update();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        return response;

    }


    //CMD_GAME_UNION_BUILD_START = 72922; // 联盟建筑开始建造
    public static Object CMD_GAME_UNION_BUILD_START(RequestParam clientParam) throws Exception {
        CSGameUnionBuildStartRequest request = CSGameUnionBuildStartRequest.parseFrom(clientParam.getData());
        CSGameUnionBuildStartResponse.Builder response = CSGameUnionBuildStartResponse.newBuilder();
        long userId = clientParam.getUserId();
        int buildId = request.getBuildId();
        UnionBuildMain unionBuidMain = UnionManager.getUnionBuildMain(buildId);
        if (unionBuidMain == null){
            return ErrorWord.BAD_PARAM;//参数错误
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostElite()) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        if (unionBuidMain.getUnlockLevel() > unionInfo.getLevel()) {
            return ErrorWord.WRONG_STATUS;//未达到解锁条件
        }
        long curTime = TimeUtils.getCurTime();
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,buildId);
        if(unionBuild != null && unionBuild.getStartTime() != 0){
            return ErrorWord.REPEATED_OPERATION;//重复开始建造
        }
        if (unionBuild == null) {
            unionBuild = new UnionBuild(unionId,buildId);
            unionBuild.putStartTime(curTime);
            unionBuild.putBuildTime( curTime + unionBuidMain.getTime());
            unionBuild.doCreate();
        } else {
            unionBuild.putStartTime(curTime);
            unionBuild.putBuildTime( curTime + unionBuidMain.getTime());
            unionBuild.update();
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionBuild);
        return response;
    }

    //CMD_GAME_UNION_BUILD_ASSIST = 72923; // 联盟建筑助力
    public static Object CMD_GAME_UNION_BUILD_ASSIST(RequestParam clientParam) throws Exception {
        CSGameUnionBuildAssistRequest request = CSGameUnionBuildAssistRequest.parseFrom(clientParam.getData());
        CSGameUnionBuildAssistResponse.Builder response = CSGameUnionBuildAssistResponse.newBuilder();
        long userId = clientParam.getUserId();
        int buildId = request.getBuildId();
        UnionBuildMain unionBuidMain = UnionManager.getUnionBuildMain(buildId);
        if (unionBuidMain == null){
            return ErrorWord.BAD_PARAM;//参数错误
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        long curTime = TimeUtils.getCurTime();
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,buildId);
        if(unionBuild == null || unionBuild.getBuildTime() <= curTime){
            return ErrorWord.REPEATED_OPERATION;//重复开始建造||已经建造完成
        }
        int num = request.getNum();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<RewardItem> consumeList = new ArrayList<>();// 总的需要消耗的道具
        for (RewardItem rewardItem : CommonUtils.takeReawrdItemFromStr(AllParam.UNION_BUILD_ASSIST_NEED_NUM)) {
            long itemNum = rewardItem.getItemNum();
            rewardItem.setItemNum(itemNum * num);
            consumeList.add(rewardItem);
        }

        if (!BagManager.checkNeedItemNum(userInfo, consumeList)) {
            return ErrorWord.ITEM_LACK;// 数量不足
        }


        RewardManager.subReward(userInfo, consumeList, pbUserData,LogType.UNION_BUILD_ASSIST);


        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionBuildLock(unionId,buildId));
            long newBuildTime = unionBuild.getBuildTime() - AllParam.UNION_BUILD_ASSIST_TIME * num;
            if (newBuildTime < curTime) {
                newBuildTime = curTime;
            }
            unionBuild.putBuildTime(newBuildTime);
            unionBuild.update();
        } catch (Exception e) {
            throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);

        } finally {
            MainService.releaseVertLock(lock);
        }



        //创建记录
        UnionBuildUserAssistRecord unionBuildUserAssistRecord = UnionManager.getUnionBuildUserAssistRecord(unionId,buildId,userId);
        if (unionBuildUserAssistRecord == null) {
            unionBuildUserAssistRecord = new UnionBuildUserAssistRecord(unionId,buildId,userId,num);
            unionBuildUserAssistRecord.doCreate();
        } else {
            unionBuildUserAssistRecord.addNum(num);
            unionBuildUserAssistRecord.update();
        }

        ProtoDataUtils.updatePBUserData(pbUserData, unionBuild);
        return response;
    }

    //CMD_GAME_UNION_BUILD_LEVEL_UP = 72924; // 联盟建筑建设(升级)
    public static Object CMD_GAME_UNION_BUILD_LEVEL_UP(RequestParam clientParam) throws Exception {
        CSGameUnionBuildLevelUpRequest request = CSGameUnionBuildLevelUpRequest.parseFrom(clientParam.getData());
        CSGameUnionBuildLevelUpResponse.Builder response = CSGameUnionBuildLevelUpResponse.newBuilder();
        long userId = clientParam.getUserId();
        int buildId = request.getBuildId();
        UnionBuildMain unionBuidMain = UnionManager.getUnionBuildMain(buildId);
        if (unionBuidMain == null){
            return ErrorWord.BAD_PARAM;//参数错误
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,buildId);
        if(unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()){
            return ErrorWord.REPEATED_OPERATION;//建筑还未建造完成
        }

        int num = request.getNum();
        int consume = AllParam.UNION_BUILD_LEVELUP_NEED_NUM;
        int exp = num * AllParam.UNION_BUILD_LEVELUP_EXP;

        if (!BagManager.checkNeedItemNum(userInfo, ItemId.TYPE_UNION_BUILD , num  * consume)) {
            return ErrorWord.ITEM_LACK;//联盟建材不足
        }
        // 执行逻辑
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        int oldEarnAdd = unionBuild.takeEarnAddEffectValue();// 升级之前对商业建筑的加成值
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionBuildLock(unionId,buildId));
            RewardManager.subReward(userInfo, ItemId.TYPE_UNION_BUILD, num  * consume, pbUserData,LogType.UNION_BUILD_LEVELUP);
            unionBuild.addExp(exp);
            unionBuild.update();
        } catch (Exception e) {
            throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);

        } finally {
            MainService.releaseVertLock(lock);
        }

        //创建记录
        UnionBuildUserRecord unionBuildUserRecord = UnionManager.getUnionBuildUserRecord(unionId,buildId,userId);
        if (unionBuildUserRecord == null) {
            unionBuildUserRecord = new UnionBuildUserRecord(unionId,buildId,userId,exp);
            unionBuildUserRecord.doCreate();
        } else {
            unionBuildUserRecord.addDayBuildCost(exp);
            unionBuildUserRecord.addBuildCost(exp);
            unionBuildUserRecord.update();
        }
        ProtoDataUtils.updatePBUserData(pbUserData, unionBuild);

        // 联盟建筑升级会对某个性格的建筑城市收益有加成作用
        int newEarnAdd = unionBuild.takeEarnAddEffectValue();// 升级后的加成值
        if (newEarnAdd > oldEarnAdd) {// 有增加
            int charType = unionBuild.takeEarnAddEffectType();// 加成性格
            int addValue = newEarnAdd - oldEarnAdd;// 增量
            UserPower userPower = GameUser.getUserPower(userId);
            JsonArray jsonArray = SkillManager.addSkillEffectArray(charType, addValue, userPower.getEarnAddUnionPerArray());
            userPower.putEarnAddUnionPer(jsonArray.toString());
            List<UserBuild> buildList = userPower.takeUserBuildList(charType);// 对应的商业建筑
            BuildManager.batchUpdateBuildEarn(pbUserData, userInfo, userPower, buildList);// 批量更新商业建筑的城市收益，并更新userpower下发给客户端
            BoardcastManager.publicUnionSyncUserPower(userInfo, unionId);// 广播给联盟其他成员 同步战力和城市收益，联盟建筑对城市收益有加成，联盟地标对战力有加成
        }

        return response;
    }


    //CMD_GAME_UNION_BUILD_LEVEL_UP_RECORD = 72925; // 联盟建筑建设记录
    public static Object CMD_GAME_UNION_BUILD_LEVEL_UP_RECORD(RequestParam clientParam) throws Exception {
        CSGameUnionBuildLevelUpRecordRequest request = CSGameUnionBuildLevelUpRecordRequest.parseFrom(clientParam.getData());
        CSGameUnionBuildLevelUpRecordResponse.Builder response = CSGameUnionBuildLevelUpRecordResponse.newBuilder();
        long userId = clientParam.getUserId();
        int buildId = request.getBuildId();
        UnionBuildMain unionBuidMain = UnionManager.getUnionBuildMain(buildId);
        if (unionBuidMain == null){
            return ErrorWord.BAD_PARAM;//参数错误
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long uniinId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(uniinId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        List<UnionBuildUserRecord> unionBuildUserRecordList = UnionManager.getUnionBuildUserRecordList(uniinId,buildId);
        for (UnionBuildUserRecord unionBuildUserRecord : unionBuildUserRecordList) {
            response.addUnionUserRecordList(unionBuildUserRecord.takeBuilder());
        }
        return response;
    }

    //CMD_GAME_UNION_BUSINESS_INIT = 72926; // 联盟运输中心初始化
    public static Object CMD_GAME_UNION_BUSINESS_INIT(RequestParam clientParam) throws Exception {
        CSGameUnionBusinessInitRequest request = CSGameUnionBusinessInitRequest.parseFrom(clientParam.getData());
        CSGameUnionBusinessInitResponse.Builder response = CSGameUnionBusinessInitResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_BUSINESS);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        UnionBusinessTaskInfo unionBusinessTaskInfo = UnionManager.getUnionBusinessTaskInfo(unionId);
        if (unionBusinessTaskInfo == null) {
            unionBusinessTaskInfo = new UnionBusinessTaskInfo(unionId);
            unionBusinessTaskInfo.insert();
        }
        ProtoDataUtils.updatePBUserData(pbUserData, unionBusinessTaskInfo);

        userUnion.countBusinessCurNum(true);//更新运输中心可用次数
        ProtoDataUtils.updatePBUserData(pbUserData, unionBuild);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        return response;
    }


    //CMD_GAME_UNION_BUSINESS_ORDER = 72927; // 联盟运输中心提交订单
    public static Object CMD_GAME_UNION_BUSINESS_ORDER(RequestParam clientParam) throws Exception {
        CSGameUnionBusinessOrderRequest request = CSGameUnionBusinessOrderRequest.parseFrom(clientParam.getData());
        CSGameUnionBusinessOrderResponse.Builder response = CSGameUnionBusinessOrderResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_BUSINESS);
        if( unionBuild.getBuildTime() == 0 || unionBuild.getBuildTime() > TimeUtils.getCurTime()){
            return ErrorWord.WRONG_STATUS;//未完成
        }
        UnionBusinessTaskInfo unionBusinessTaskInfo = UnionManager.getUnionBusinessTaskInfo(unionId);
        if (unionBusinessTaskInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未完成
        }
        int taskId = unionBusinessTaskInfo.getTaskId();
        UnionBusiness unionBusiness = UnionManager.getUnionBusiness(taskId);
        int needNum = unionBusiness.getNum() - unionBusinessTaskInfo.getNum();
        if (needNum <= 0) {
            return ErrorWord.ALREADY_MAX;//任务已完成
        }
        int num = request.getNum();//用户操作次数
        int businessNum = userUnion.countBusinessCurNum(false);
        if(businessNum < num) {
            return ErrorWord.ITEM_LACK;//次数不足
        }
        int orderNum = num;
        int addOrderNumTotal = 0;//建筑等级带来的订单额外完成总次数

        //建筑效果 额外订单次数
        for (int i = 0 ; i < orderNum; i++) {
            UnionBuildUpgrade unionBuildUpgrade = UnionManager.getUnionBuildUpgrade(UnionBuildMain.BUILD_ID_BUSINESS, unionBuild.getLevel());
            int addRate = unionBuildUpgrade.getEffectTypeValue(UnionBuildUpgrade.EFFECT_TYPE_BUSINESS);//万分比
            int addOrderRate = Tool.getRandom(0,10000);
            int addOrderNum = addOrderRate < addRate ? 1: 0;//是否随机额外订单次数+1
            addOrderNumTotal += addOrderNum;
        }
        orderNum += addOrderNumTotal;
        orderNum = needNum > orderNum ? orderNum :  needNum;

        //更新运输中心用户可次数
        userUnion.addBusinessNum(-(orderNum - addOrderNumTotal));
        userUnion.addBusinessDayNum(orderNum);
        userUnion.addBusinessTotalNum(orderNum);
        userUnion.update();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        //获得金币奖励
        long glodNum = unionInfo.getPower() * AllParam.UNION_BUSINESS_ORDER_GOLD_REWARD / 100;
        RewardManager.addReward(userInfo, ItemId.GOLD, glodNum * orderNum , pbUserData,LogType.UNION_BUSINESS_ORDER,orderNum);

        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionBusinessLock(unionId));
            //更新联盟运输中心订单进度
            unionBusinessTaskInfo.addNum(orderNum);
            if (orderNum == needNum) {
                //创建联盟动态
                UnionManager.addUnionDynamicRecord(unionId, MailConstant.UNION_DYNAMIC_ORDER,unionBusinessTaskInfo.getTaskId());
                //刷新任务
                unionBusinessTaskInfo.sendBuissnessReward(unionBusiness);
            }
            unionBusinessTaskInfo.update();
        } catch (Exception e) {
            throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);

        } finally {
            MainService.releaseVertLock(lock);
        }

        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        ProtoDataUtils.updatePBUserData(pbUserData, unionBusinessTaskInfo);
        return response;
    }

    //CMD_GAME_UNION_BUSINESS_RECORD = 72928; // 联盟运输中心记录列表
    public static Object CMD_GAME_UNION_BUSINESS_RECORD(RequestParam clientParam) throws Exception {
        CSGameUnionBusinessRecordRequest request = CSGameUnionBusinessRecordRequest.parseFrom(clientParam.getData());
        CSGameUnionBusinessRecordResponse.Builder response = CSGameUnionBusinessRecordResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_BUSINESS);
        if( unionBuild.getBuildTime() == 0 || unionBuild.getBuildTime() > TimeUtils.getCurTime()){
            return ErrorWord.WRONG_STATUS;//未完成
        }
        UnionBusinessTaskInfo unionBusinessTaskInfo = UnionManager.getUnionBusinessTaskInfo(unionId);
        if (unionBusinessTaskInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未完成
        }
        List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
        for (UnionMember unionMember : unionMemberList) {
            UserUnion userUnionMember = UnionManager.getUserUnion(unionMember.getUserId());
            response.addRecordList(UnionManager.takePBUnionUserRecordBuilder(userUnionMember.getId(),userUnionMember.getBusinessDayNum(),userUnionMember.getBusinessTotalNum(),3));
        }
        return response;
    }


    //CMD_GAME_UNION_CHARGE_INFO = 72929; // 联盟限时充值初始化
    public static Object CMD_GAME_UNION_CHARGE_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionChargeInfoRequest request = CSGameUnionChargeInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionChargeInfoResponse.Builder response = CSGameUnionChargeInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        JsonArray actChargeTimeArray = UnionManager.getUnionActChargeTime();
        if(actChargeTimeArray.size() == 0) {
            return ErrorWord.INVALID_OPERATION;//时间未配置,暂不开放活动
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();

        UnionActChargeInfo unionActChargeInfo = UnionManager.getUnionActChargeInfo(unionId);
        if (unionActChargeInfo != null) {
            ProtoDataUtils.updatePBUserData(pbUserData, unionActChargeInfo);
        }


        String startDayStr = TimeUtils.getDayStr(actChargeTimeArray.getLong(0));
        String recordKey = RedisKey.getUnionActChargeRecordKey(unionId,startDayStr);
        JsonArray list = Future.await(RedisTools.getRankListByIndex(recordKey, 0,  - 1, false));
        for (int i = 0; i < list.size(); i++) {
            long recordUserId = Long.parseLong(list.getString(i));
            response.addList(UnionManager.takePBUnionUserRecordBuilder(recordUserId,0,0,5));
        }
        response.setStartTime(actChargeTimeArray.getLong(0));
        response.setEndTime(actChargeTimeArray.getLong(1));
        return response;
    }

    //CMD_GAME_UNION_CHARGE_REWRD = 72930; // 联盟限时充值领奖
    public static Object CMD_GAME_UNION_CHARGE_REWRD(RequestParam clientParam) throws Exception {
        CSGameUnionChargeRewrdRequest request = CSGameUnionChargeRewrdRequest.parseFrom(clientParam.getData());
        CSGameUnionChargeRewrdResponse.Builder response = CSGameUnionChargeRewrdResponse.newBuilder();
        long userId = clientParam.getUserId();
        int num = request.getNum();
        UnionAccumulation unionAccumulation = UnionManager.getUnionAccumulation(num);
        if (unionAccumulation == null) {
            return ErrorWord.BAD_PARAM;
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        JsonArray actChargeTimeArray = UnionManager.getUnionActChargeTime();
        if(actChargeTimeArray.size() == 0) {
            return ErrorWord.INVALID_OPERATION;//时间未配置,暂不开放活动
        }
        long startTime = actChargeTimeArray.getLong(0);
        long endTime = actChargeTimeArray.getLong(1);
        long curTime = TimeUtils.getCurTime();
        if (curTime < startTime || curTime > endTime) {
            return ErrorWord.WRONG_STATUS;
        }
        UnionActChargeInfo unionActChargeInfo = UnionManager.getUnionActChargeInfo(unionId);
        if (unionActChargeInfo == null || unionActChargeInfo.getNum() < unionAccumulation.getNum()) {
            //未达标
            return ErrorWord.NOT_DATA_4;
        }
        List<Integer> userActChargeRewardList = userUnion.getUserActChargeRewardList();
        if (userActChargeRewardList.indexOf(num) != -1) {
            return ErrorWord.ALREADY_MAX;//已经领取过
        }
        userActChargeRewardList.add(num);
        String userActChargeRewardStr = userActChargeRewardList.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(";"));
        userUnion.putActChargeReward(userActChargeRewardStr);
        userUnion.update();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        //领取充值档位奖励
        RewardManager.addReward(userInfo, unionAccumulation.getReward() , pbUserData,LogType.UNION_ACT_CHARGE_REWARD,num);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        return response;
    }

    //CMD_GAME_UNION_DISCOUNT_SHOP = 72931; // 联盟折扣商店初始化
    public static Object CMD_GAME_UNION_DISCOUNT_SHOP(RequestParam clientParam) throws Exception {
        CSGameUnionDiscountShopRequest request = CSGameUnionDiscountShopRequest.parseFrom(clientParam.getData());
        CSGameUnionDiscountShopResponse.Builder response = CSGameUnionDiscountShopResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        //获取联盟总部建筑信息
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_MAIN);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }
        //获取联盟折扣商店信息
        UnionDiscountShopInfo unionDiscountShopInfo  = UnionManager.getUnionDiscountShopInfo(unionId);
        if( unionDiscountShopInfo == null) {
            unionDiscountShopInfo = new UnionDiscountShopInfo(unionId);
            unionDiscountShopInfo.insert();
        }
        //获取折扣商店砍价记录
        long curTime = TimeUtils.getCurTime();
        String dayStr = TimeUtils.getDayStr(curTime);
        String recordKey = RedisKey.getUnionDiscountShopRecordKey(unionId,dayStr);
        JsonArray list = Future.await(RedisTools.getRankListByIndex(recordKey, 0,  - 1, true));
        for (int i = 0; i < list.size(); i++) {
            if (i % 2 == 0) {// userid
                long recordUserId = Long.parseLong(list.getString(i));
                double score = Double.parseDouble(list.getString(i + 1));
                response.addList(UnionManager.takePBUnionUserRecordBuilder(recordUserId, (int) score,0,4));
            }
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionDiscountShopInfo,true);
        return response;
    }

    //CMD_GAME_UNION_DISCOUNT_SHOP_START = 72932; // 联盟折扣商店开始砍价
    public static Object CMD_GAME_UNION_DISCOUNT_SHOP_START(RequestParam clientParam) throws Exception {
        CSGameUnionDiscountShopStartRequest request = CSGameUnionDiscountShopStartRequest.parseFrom(clientParam.getData());
        CSGameUnionDiscountShopStartResponse.Builder response = CSGameUnionDiscountShopStartResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        int discountShopPrice = userUnion.getDiscountShopPrice();
        if (discountShopPrice != 0) {
            return ErrorWord.REPEATED_OPERATION;//已经砍过价
        }

        //获取联盟总部建筑信息
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_MAIN);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        UnionDiscountShopInfo unionDiscountShopInfo  = UnionManager.getUnionDiscountShopInfo(unionId);
        if(unionDiscountShopInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        if (unionDiscountShopInfo.getDiscountPrice() >= unionDiscountShopInfo.getInitPrice()) {
            return ErrorWord.ALREADY_MAX;// 已经砍到0了
        }

        int priceStart = AllParam.UNION_DISCOUNT_SHOP_PRICE[0];
        int priceEnd = AllParam.UNION_DISCOUNT_SHOP_PRICE[1];

        int random = Tool.getRandom(priceStart, priceEnd);
//        UnionBuildUpgrade unionBuildUpgrade = UnionManager.getUnionBuildUpgrade(UnionBuildMain.BUILD_ID_DISCOUNT_SHOP,unionBuild.getLevel());
//        int buildAdd = unionBuildUpgrade.getEffectTypeValue(UnionBuildUpgrade.EFFECT_TYPE_DISCOUNT_SHOP);// 建筑加成6000 表示60%
        //每次减免金额=礼包价格*3%*（10000+砍价区间）/ 10000
        double initPrice = (double) unionDiscountShopInfo.getInitPrice();// 初始价格
        double price = initPrice * 3 / 100 * (10000 + random ) / 10000;
        int discountPrice = (int) Math.floor(price);// 向下取整
        //System.out.println("random:" + random + " buildadd:" + buildAdd + " initPrice: " + initPrice + " price:" + price + " discountPrice:" + discountPrice);

        if (discountPrice + unionDiscountShopInfo.getDiscountPrice() >= unionDiscountShopInfo.getInitPrice()) {
            discountPrice = unionDiscountShopInfo.getInitPrice() - unionDiscountShopInfo.getDiscountPrice();// 不能超过初始价格
        }

        unionDiscountShopInfo.addDiscountPrice(discountPrice);
        unionDiscountShopInfo.update();

        long curTime = TimeUtils.getCurTime();
        String dayStr = TimeUtils.getDayStr(curTime);
        String unionDiscountShopRecordKey = RedisKey.getUnionDiscountShopRecordKey(unionId,dayStr);
        boolean isExists = Future.await(RedisTools.exists(unionDiscountShopRecordKey));
        RedisTools.addRank(unionDiscountShopRecordKey, userId, discountPrice);
        if (!isExists) {
            RedisTools.expire(unionDiscountShopRecordKey, 3 * TimeUtils.DAY);//保留3天联盟充值记录
        }

        JsonArray list = Future.await(RedisTools.getRankListByIndex(unionDiscountShopRecordKey, 0,  - 1, true));
        for (int i = 0; i < list.size(); i++) {
            if (i % 2 == 0) {// userid
                long recordUserId = Long.parseLong(list.getString(i));
                double score = Double.parseDouble(list.getString(i + 1));
                response.addList(UnionManager.takePBUnionUserRecordBuilder(recordUserId, (int) score,0,4));
            }
        }

        userUnion.putDiscountShopPrice(discountPrice);
        userUnion.update();

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        ProtoDataUtils.updatePBUserData(pbUserData, unionDiscountShopInfo,true);
        return response;
    }

    //CMD_GAME_UNION_DISCOUNT_SHOP_BUY = 72933; // 联盟折扣商店购买
    public static Object CMD_GAME_UNION_DISCOUNT_SHOP_BUY(RequestParam clientParam) throws Exception {
        CSGameUnionDiscountShopBuyRequest request = CSGameUnionDiscountShopBuyRequest.parseFrom(clientParam.getData());
        CSGameUnionDiscountShopBuyResponse.Builder response = CSGameUnionDiscountShopBuyResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        if (userUnion.getIsDiscountShopBuy() == 1) {
            return ErrorWord.ALREADY_MAX;//已经购买
        }

        UnionDiscountShopInfo unionDiscountShopInfo  = UnionManager.getUnionDiscountShopInfo(unionId);
        if(unionDiscountShopInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }
        int shopId = unionDiscountShopInfo.getShopId();

        UnionDiscountShop unionDiscountShop = UnionManager.getUnionDiscountShop(shopId);
        if (unionDiscountShop == null) {
            return ErrorWord.BAD_PARAM;//配置表错误 无商品id
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        int discountPrice = unionDiscountShopInfo.getDiscountPrice();
        int initPrice = unionDiscountShopInfo.getInitPrice();
        int cost = initPrice < discountPrice ? 0 : initPrice - discountPrice;
        if (cost > 0) {
            //判断道具是否足够
            if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, AllParam.UNION_CREATE_NEED_DIAMOND_NUM)) {
                return ErrorWord.ITEM_LACK;//道具不足
            }
            RewardManager.subReward(userInfo, ItemId.DIAMOND, cost, pbUserData,LogType.UNION_DISCOUNT_SHOP_BUY);
        }
        userUnion.putIsDiscountShopBuy((byte) 1);
        userUnion.update();
        RewardManager.addReward(userInfo, unionDiscountShop.getReward(), pbUserData,LogType.UNION_DISCOUNT_SHOP_BUY,shopId,cost);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion,false);
        return response;
    }

    //CMD_GAME_UNION_BOSS_INFO = 72934; // 联盟远征信息初始化
    public static Object CMD_GAME_UNION_BOSS_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionBossInfoRequest request = CSGameUnionBossInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionBossInfoResponse.Builder response = CSGameUnionBossInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_BOSS);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        UnionBossInfo unionBossInfo = UnionManager.getUnionBossInfo(unionId);
        if (unionBossInfo == null) {
            unionBossInfo = new UnionBossInfo(unionId);
            unionBossInfo.insert();
        }

        //是否领取排行榜奖励

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionBossInfo,true);
        return response;
    }

    //CMD_GAME_UNION_BOSS_POWER_ADD = 72935; // 联盟远征战力加成
    public static Object CMD_GAME_UNION_BOSS_POWER_ADD(RequestParam clientParam) throws Exception {
        CSGameUnionBossPowerAddRequest request = CSGameUnionBossPowerAddRequest.parseFrom(clientParam.getData());
        CSGameUnionBossPowerAddResponse.Builder response = CSGameUnionBossPowerAddResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        if (userUnion.getBossAddPowerNum() >= AllParam.UNION_BOSS_ADD_POWER_MAXNUM) {
            return ErrorWord.ALREADY_MAX;//购买达最大上限
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        UnionBossInfo unionBossInfo = UnionManager.getUnionBossInfo(unionId);
        if (unionBossInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        String costItemStr = AllParam.UNION_BOSS_ADD_POWER_COST;
        if (!BagManager.checkNeedItemNum(userInfo,  CommonUtils.takeReawrdItemFromStr(costItemStr))) {
            return ErrorWord.ITEM_LACK;//道具不足
        }
        //扣除道具,增加购买次数
        RewardManager.subReward(userInfo, costItemStr, pbUserData,LogType.UNION_BOSS_PAY_ADD_POWER);
        userUnion.addBossAddPowerNum(1);
        userUnion.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        return response;
    }

    //CMD_GAME_UNION_BOSS_FIGHT = 72936; // 联盟远征挑战
    public static Object CMD_GAME_UNION_BOSS_FIGHT(RequestParam clientParam) throws Exception {
        CSGameUnionBossFightRequest request = CSGameUnionBossFightRequest.parseFrom(clientParam.getData());
        CSGameUnionBossFightResponse.Builder response = CSGameUnionBossFightResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        //计算次数
        boolean isFree = false;
        int bossNum = userUnion.getBossFreeNum() ;//联盟远征boss攻打次数
        if (bossNum < AllParam.UNION_BOSS_FLIGHT_FREE_NUM) {
            //今日攻打次数小于配置的免费次数
            isFree = true;
        }
        if(!isFree) {
            //判断是否购买攻打次数
            if (userUnion.getBossBuyNum() <= (bossNum - AllParam.UNION_BOSS_FLIGHT_FREE_NUM)) {
                return ErrorWord.TIMES_LACK;//次数不足
            }
        }

        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_BOSS);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        UnionBossInfo unionBossInfo = UnionManager.getUnionBossInfo(unionId);
        if (unionBossInfo == null) {
            return ErrorWord.WRONG_STATUS;//boss数据未生成
        }
        int stageId = unionBossInfo.getStageId();
        long beforeHp = unionBossInfo.getHp();
        response.setBeforeHp(beforeHp);

        UserPower userPower = GameUser.getUserPower(userId);
        long lastPower = userPower.getPower();
        int bossAddPowerNum = userUnion.getBossAddPowerNum();//购买战力加成次数
        //建筑等级加成
        UnionBuildUpgrade unionBuildUpgrade = UnionManager.getUnionBuildUpgrade(UnionBuildMain.BUILD_ID_BOSS, unionBuild.getLevel());
        int buildUpgradeAdd = unionBuildUpgrade.getEffectTypeValue(UnionBuildUpgrade.EFFECT_TYPE_BOSS);//建筑等级额外次数 (万分比)
        if (bossAddPowerNum > 0) {
            //已购买加成次数 ,计算加成后的伤害
            List<UserPartner> userPartnerList = PartnerManager.getUserPartnerList(userId);
            for (UserPartner userPartner : userPartnerList){
                long addPower = userPartner.getTotalPower() * (userUnion.getBossAddPowerNum() * AllParam.UNION_BOSS_ADD_POWER + buildUpgradeAdd) / 100;
                lastPower += addPower;
            }
        }


        long fightPower = lastPower > beforeHp ? beforeHp  : lastPower ;
        long hp = beforeHp - fightPower;

        //更新伤害记录
        UnionBossUserRecord unionBossUserRecord = UnionManager.getUnionBossUserRecord(unionId,stageId,userId);
        if (unionBossUserRecord == null) {
            unionBossUserRecord = new UnionBossUserRecord(unionId,stageId,userId,fightPower);
            unionBossUserRecord.doCreate();
        } else {
            unionBossUserRecord.addHp(fightPower);
            unionBossUserRecord.update();
        }
        userUnion.putBossAddPowerNum(0);
        userUnion.addBossFreeNum(1);
        userUnion.update();

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();

        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionBossLock(unionId));
            UnionBossStage unionBossStage = UnionManager.getUnionBossStage(stageId);
            if(hp == 0) {
                //血量为0,自动进入下一只boss
                int nextId = unionBossInfo.getStageId();
                ConcurrentHashMap<Integer, UnionBossStage> unionBossStageMap =  UnionManager.getUnionBossStageMap();
                if (nextId < unionBossStageMap.size()) {
                    nextId += 1;
                }
                UnionBossStage nextUnionBossStage = UnionManager.getUnionBossStage(nextId);
                unionBossInfo.putStageId(nextId);
                unionBossInfo.putInitHp(nextUnionBossStage.getPower());
                unionBossInfo.putHp(nextUnionBossStage.getPower());
                //发放最后一击奖励
                MailManager.sendSystemMailReplaceContent(userId, MailConstant.UNION_BOSS_KILL_REWARD_TITLE, MailConstant.UNION_BOSS_KILL_REWARD_CONTENT, unionBossStage.getKillRewardItemList(), LogType.UNION_BOSS_FLIGHT_REWARD, stageId,stageId);
                //发放排行榜奖励
                List<UnionBossUserRecord> unionBossUserRecordList = UnionManager.getUnionBossUserRecordList(unionId,stageId);
                for (int i = 0; i < unionBossUserRecordList.size(); i++){
                    UnionBossUserRecord unionBossUserRecordTmp = unionBossUserRecordList.get(i);
                    long memberId = unionBossUserRecordTmp.getUserId();
                    UserUnion userUnionMember = UnionManager.getUserUnion(memberId);
                    if (userUnionMember.getUnionId() != unionId) {
                        continue;
                    }
                    RankReward rankReward = RankManager.getRankReward(unionBossStage.getRankType(),i+1);
                    List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(rankReward.getReward());// 奖励
                    UserUnionBossReward userUnionBossReward = UnionManager.getUserUnionBossReward(memberId,stageId);
                    if (userUnionBossReward == null) {
                        //未领取过奖励 ,进行发奖
                        userUnionBossReward = new UserUnionBossReward(memberId,stageId,unionId,i);
                        userUnionBossReward.doCreate();
                        MailManager.sendSystemMailReplaceContent(memberId, MailConstant.UNION_BOSS_RANK_REWARD_TITLE, MailConstant.UNION_BOSS_RANK_REWARD_CONTENT, rewardItemList, LogType.UNION_BOSS_FLIGHT_REWARD, stageId,stageId,i+1);
                    } else {
                        //已领取过奖励,进行邮件通知
                        MailManager.sendSystemMailReplaceContent(memberId, MailConstant.UNION_BOSS_RANK_NO_REWARD_TITLE, MailConstant.UNION_BOSS_RANK_NO_REWARD_CONTENT, new ArrayList<>(), LogType.UNION_BOSS_FLIGHT_REWARD, stageId,stageId);
                    }
                }
            } else {
                unionBossInfo.putHp(hp);
            }
            unionBossInfo.update();

            RewardManager.addReward(userInfo, unionBossStage.getFightRewardItemList(), pbUserData, LogType.UNION_BOSS_FLIGHT_REWARD,stageId);

        } catch (Exception e) {
            throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);

        } finally {
            MainService.releaseVertLock(lock);
        }

        ProtoDataUtils.updatePBUserData(pbUserData, unionBossInfo,true);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        return response;
    }

    //CMD_GAME_UNION_BOSS_CHAT = 72937; // 联盟远征集结令
    public static Object CMD_GAME_UNION_BOSS_CHAT(RequestParam clientParam) throws Exception {
        CSGameUnionBossChatRequest request = CSGameUnionBossChatRequest.parseFrom(clientParam.getData());
        CSGameUnionBossChatResponse.Builder response = CSGameUnionBossChatResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_BOSS);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        UnionBossInfo unionBossInfo = UnionManager.getUnionBossInfo(unionId);
        if (unionBossInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }
        if ((unionBossInfo.getChatTime() + AllParam.UNION_BOSS_CHAT_CD_TIME) > TimeUtils.getCurTime()) {
            return ErrorWord.STILL_IN_CDTIME;//cd时间未到
        }
        unionBossInfo.putChatTime(TimeUtils.getCurTime());
        unionBossInfo.update();

        //发布集结令
        String content = ChatManager.getSystemMsg(MailConstant.UNION_BOSS_CHAT);
        String params = "{\"link\":[{\"linkType\":10213,\"values\":\"[]\"}]}";
        ChatUnion chatUnion = new ChatUnion(userInfo, ChatManager.CHAT_SUB_TYPE_COMMON, unionId, content, params);
        chatUnion.doCreate();

        // 广播给玩家
        Common.PBChatMsg.Builder chatMsgBuilder = chatUnion.takeBuilder();
        BoardcastManager.publicChatMessage(userInfo, chatMsgBuilder);

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionBossInfo);
        response.setChatMsg(chatMsgBuilder);

        return response;
    }

    //CMD_GAME_UNION_BOSS_FIGHT_BUY = 72938; // 联盟远征挑战购买
    public static Object CMD_GAME_UNION_BOSS_FIGHT_BUY(RequestParam clientParam) throws Exception {
        CSGameUnionBossFightBuyRequest request = CSGameUnionBossFightBuyRequest.parseFrom(clientParam.getData());
        CSGameUnionBossFightBuyResponse.Builder response = CSGameUnionBossFightBuyResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        if (userUnion.getBossBuyNum() >= AllParam.UNION_BOSS_FLIGHT_PAY_NUM) {
            return ErrorWord.ALREADY_MAX;//购买达最大上限
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        UnionBossInfo unionBossInfo = UnionManager.getUnionBossInfo(unionId);
        if (unionBossInfo == null) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, AllParam.UNION_BOSS_FLIGHT_BAY_COST)) {
            return ErrorWord.ITEM_LACK;//钻石不足
        }
        //扣除道具,增加购买次数
        RewardManager.subReward(userInfo, ItemId.DIAMOND,AllParam.UNION_BOSS_FLIGHT_BAY_COST, pbUserData,LogType.UNION_BOSS_PAY_FLIGHT_NUM);
        userUnion.addBossBuyNum(1);
        userUnion.update();

        ProtoDataUtils.updatePBUserData(pbUserData, userUnion);
        return response;
    }

    //CMD_GAME_UNION_BOSS_RANK = 72939; // 联盟远征排行榜
    public static Object CMD_GAME_UNION_BOSS_RANK(RequestParam clientParam) throws Exception {
        CSGameUnionBossRankRequest request = CSGameUnionBossRankRequest.parseFrom(clientParam.getData());
        CSGameUnionBossRankResponse.Builder response = CSGameUnionBossRankResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        int stageId = request.getId();
        Common.PBRankInfo.Builder pbRankInfo = Common.PBRankInfo.newBuilder();
        List<UnionBossUserRecord> unionBossUserRecordList = UnionManager.getUnionBossUserRecordList(unionId,stageId);
        for (int i = 0; i < unionBossUserRecordList.size(); i++) {
            UnionBossUserRecord unionBossUserRecord = unionBossUserRecordList.get(i);
            if (unionBossUserRecord.getUserId() == userId) {
                pbRankInfo.setMyScore(unionBossUserRecord.getHp());
                pbRankInfo.setMyRank(i+1);
            }
            pbRankInfo.addMembers(unionBossUserRecord.takePbRankInfoBuilder().build());
        }
        response.putRankInfo(RankConstant.SERVER_RANK_UNION_BOSS,pbRankInfo.build());
        return response;
    }

    //  CMD_GAME_UNION_BOX_MAIN_INFO = 72940; // 联盟宝箱界面信息 [2]每次打开请求
    public static Object CMD_GAME_UNION_BOX_MAIN_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionBoxMainInfoRequest request = CSGameUnionBoxMainInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionBoxMainInfoResponse.Builder response = CSGameUnionBoxMainInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        int type = request.getType();
        if (type != UnionConstant.UNION_GIFT_BOX_TYPE_1 && type != UnionConstant.UNION_GIFT_BOX_TYPE_2) {
            return ErrorWord.BAD_PARAM;//类型错误
        }

        // 1、联盟宝箱进度
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UnionBoxInfo unionBoxInfo = UnionManager.getUnionBoxInfo(unionId);
        if (unionBoxInfo == null) {
            Lock lock = null;
            try {
                lock = MainService.getVertLock(LockKey.getUnionBoxLock(unionId));
                unionBoxInfo = UnionManager.getUnionBoxInfo(unionId);
                if (unionBoxInfo == null) {
                    unionBoxInfo = new UnionBoxInfo(unionId, unionInfo.getLevel());
                    unionBoxInfo.insert();
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to acquire union box lock for unionId: " + unionId, e);
            } finally {
                MainService.releaseVertLock(lock);
            }
        }
        ProtoDataUtils.updatePBUserData(pbUserData, unionBoxInfo, true);

        // 2、礼盒列表
        List<UnionGiftBoxList> unionGiftBoxListList = UnionManager.getUnionGiftBoxList(unionId);
        List<Long> receiveGiftBoxRecordIds = UnionManager.getReceiveGiftBoxRecordIds(unionId, userId);
        for (UnionGiftBoxList unionGiftBoxList : unionGiftBoxListList) {
            long giftBoxListId = unionGiftBoxList.getId();
            if (unionGiftBoxList.getType() != type || unionGiftBoxList.getUserId() == userId) { // 不是当前类型
                continue;
            }

            if (Tool.isInList(receiveGiftBoxRecordIds, giftBoxListId)) { // 已经领取过
                continue;
            }
            pbUserData.getUnionBuilder().getUnionBoxMainInfoBuilder().putUnionGiftBoxList(unionGiftBoxList.getId(), UnionManager.takePBUnionGiftBoxListBuilder(unionGiftBoxList).build());
        }

        // 3、用户领取联盟宝箱的数据
        UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
        ProtoDataUtils.updatePBUserData(response.getUserBuilder(), userUnionBox, true);
        return response;
    }

    //  CMD_GAME_UNION_GIFT_BOX_REWARD = 72941; // 联盟礼盒领取奖励
    public static Object CMD_GAME_UNION_GIFT_BOX_REWARD(RequestParam clientParam) throws Exception {
        CSGameUnionGiftBoxRewardRequest request = CSGameUnionGiftBoxRewardRequest.parseFrom(clientParam.getData());
        CSGameUnionGiftBoxRewardResponse.Builder response = CSGameUnionGiftBoxRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.NOT_DATA_4;
        }
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_MAIN);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        long giftBoxId = request.getId();
        List<UserUnionGiftBoxRecord> userUnionGiftBoxRecordList = UnionManager.getUserUnionGiftBoxRecordList(userId);
        if (!userUnionGiftBoxRecordList.isEmpty() && userUnionGiftBoxRecordList.stream().anyMatch(x -> x.getGiftBoxId() == giftBoxId)) { // 已经领取过
            return ErrorWord.NOT_DATA_5;
        }

        List<UnionGiftBoxList> unionGiftBoxListList = UnionManager.getUnionGiftBoxList(unionId);
        if (unionGiftBoxListList.isEmpty() || unionGiftBoxListList.stream().noneMatch(x -> x.getId() == giftBoxId)) { // 没有这个礼盒
            return ErrorWord.NOT_DATA_6;
        }

        UnionGiftBoxList unionGiftBoxList = unionGiftBoxListList.stream().filter(x -> x.getId() == giftBoxId).findFirst().get();

        if (unionGiftBoxList.getUserId() == userId) { // 不能领取自己的礼盒，自己的完成的时候就自动领取了
            return ErrorWord.NOT_DATA_7;
        }

        UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
        //计算可使用次数
        UnionBuildUpgrade unionBuildUpgrade = UnionManager.getUnionBuildUpgrade(UnionBuildMain.BUILD_ID_BUSINESS, unionBuild.getLevel());
        int buildUpgradeNum = unionBuildUpgrade.getEffectTypeValue(UnionBuildUpgrade.EFFECT_TYPE_MAIN);//建筑等级额外次数
        int maxNum = AllParam.UNION_ACTIVE_GIFT_BOX_DAILY_RECEIVE_MAX +buildUpgradeNum;

        if (userUnionBox.getReceiveActiveBoxNum() >= maxNum) {
            return ErrorWord.NOT_DATA_8;
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UnionManager.insertUserUnionGiftBoxRecord(userId, unionGiftBoxList);

        if (unionGiftBoxList.getType() == UnionConstant.UNION_GIFT_BOX_TYPE_1) { // 添加活跃礼盒的领取数
            userUnionBox.addReceiveActiveBoxNum(1);
            userUnionBox.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userUnionBox);
        }
        ProtoDataUtils.deletePBUserData(pbUserData, unionGiftBoxList);
        List<RewardItem> takeRewardList = CommonUtils.takeReawrdItemFromStr(unionGiftBoxList.getReward());
        // 发送奖励
        RewardManager.addReward(userInfo, takeRewardList, pbUserData, LogType.UNION_GIFT_BOX_REWARD, unionId,giftBoxId,unionGiftBoxList.getType());

        ThinkingDataManager.pushUserUnionGiftBoxRewardEvent(userInfo, unionGiftBoxList.getType());// 数数上报数据

        return response;

    }
    //  CMD_GAME_UNION_ONE_KEY_GIFT_BOX_REWARD = 72942; // 联盟礼盒一键领取奖励
    public static Object CMD_GAME_UNION_ONE_KEY_GIFT_BOX_REWARD(RequestParam clientParam) throws Exception {
        CSGameUnionOneKeyGiftBoxRewardRequest request = CSGameUnionOneKeyGiftBoxRewardRequest.parseFrom(clientParam.getData());
        CSGameUnionOneKeyGiftBoxRewardResponse.Builder response = CSGameUnionOneKeyGiftBoxRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.NOT_DATA_2;
        }

        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_MAIN);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return ErrorWord.WRONG_STATUS;//建筑未建造完成
        }

        int type = request.getType();
        if (type != UnionConstant.UNION_GIFT_BOX_TYPE_1 && type != UnionConstant.UNION_GIFT_BOX_TYPE_2) {
            return ErrorWord.BAD_PARAM;//类型错误
        }

        List<UnionGiftBoxList> unionGiftBoxListList = UnionManager.getUnionGiftBoxList(unionId);
        if (unionGiftBoxListList.isEmpty()) { // 没有礼盒
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        List<Long> receiveGiftBoxRecordIds = UnionManager.getReceiveGiftBoxRecordIds(unionId, userId);
        List<UnionGiftBoxList> takeList = unionGiftBoxListList.stream().filter(x -> x.getType() == type && x.getUserId() != userId && !receiveGiftBoxRecordIds.contains(x.getId())).toList();
        if (takeList.isEmpty()) {
            return ErrorWord.NOT_DATA_4;
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<RewardItem> takeRewardList = new ArrayList<>();
        List<UnionGiftBoxList> finalTakeList = takeList;
        if (type == UnionConstant.UNION_GIFT_BOX_TYPE_1) {
            UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
            //计算可使用次数
            UnionBuildUpgrade unionBuildUpgrade = UnionManager.getUnionBuildUpgrade(UnionBuildMain.BUILD_ID_BUSINESS, unionBuild.getLevel());
            int buildUpgradeNum = unionBuildUpgrade.getEffectTypeValue(UnionBuildUpgrade.EFFECT_TYPE_MAIN);//建筑等级额外次数
            int maxNum = AllParam.UNION_ACTIVE_GIFT_BOX_DAILY_RECEIVE_MAX + buildUpgradeNum;
            int receiveMaxNum = maxNum - userUnionBox.getReceiveActiveBoxNum();
            if (receiveMaxNum <= 0) { // 超过领取上限了
                return ErrorWord.NOT_DATA_5;
            }
            if (receiveMaxNum > takeList.size()) {
                userUnionBox.addReceiveActiveBoxNum(takeList.size());
            } else {
                // 激活时间排序，最早优先领取, 取前receiveMaxNum个
                finalTakeList = takeList.stream()
                        .sorted(Comparator.comparingLong(UnionGiftBoxList::getActivateTime))
                        .limit(receiveMaxNum)
                        .toList();
                userUnionBox.addReceiveActiveBoxNum(receiveMaxNum);
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userUnionBox);
        }
        List<RewardItem> specialTakeRewardList = new ArrayList<>();
        for (UnionGiftBoxList unionGiftBoxList : finalTakeList) {
            if (unionGiftBoxList.getType() == UnionConstant.UNION_GIFT_BOX_TYPE_1) {
                specialTakeRewardList.addAll(CommonUtils.takeReawrdItemFromStr(unionGiftBoxList.getReward()));
            }else{
                takeRewardList.addAll(CommonUtils.takeReawrdItemFromStr(unionGiftBoxList.getReward()));
            }
            UnionManager.insertUserUnionGiftBoxRecord(userId, unionGiftBoxList);
            ProtoDataUtils.deletePBUserData(pbUserData, unionGiftBoxList);

            ThinkingDataManager.pushUserUnionGiftBoxRewardEvent(userInfo, unionGiftBoxList.getType());// 数数上报数据
        }
        if (!specialTakeRewardList.isEmpty()) {
            RewardManager.addReward(userInfo, specialTakeRewardList, pbUserData, LogType.UNION_GIFT_BOX_REWARD,unionId, UnionConstant.UNION_GIFT_BOX_TYPE_1);
        }
        if (!takeRewardList.isEmpty()) {
            RewardManager.addReward(userInfo, takeRewardList, pbUserData, LogType.UNION_GIFT_BOX_REWARD,unionId);
        }
        response.setType(type);
        return response;
    }

    //  CMD_GAME_UNION_DISPOSABLE_BOX_PROGRESS_REWARD = 72943; // 联盟一次性领取宝箱进度奖励
    public static Object CMD_GAME_UNION_DISPOSABLE_BOX_PROGRESS_REWARD(RequestParam clientParam) throws Exception {
        CSGameUnionDisposableBoxProgressRewardRequest request = CSGameUnionDisposableBoxProgressRewardRequest.parseFrom(clientParam.getData());
        CSGameUnionDisposableBoxProgressRewardResponse.Builder response = CSGameUnionDisposableBoxProgressRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        UnionBoxInfo unionBoxInfo = UnionManager.getUnionBoxInfo(unionId);
        if (unionBoxInfo == null) {
            return ErrorWord.NOT_DATA_4;
        }

        UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
        if (userUnionBox == null) {
            return ErrorWord.NOT_DATA_5;
        }

        // 没有奖励可领取
        int totalNum = unionBoxInfo.getTotalNum();
        int receiveBoxNum = userUnionBox.getReceiveBoxNum();
        if (receiveBoxNum >= totalNum) {
            return ErrorWord.ITEM_LACK;
        }

        List<RewardItem> takeRewardList = new ArrayList<>();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        if (unionBoxInfo.getBoxId() > userUnionBox.getReceiveBoxId()) { // 先领取未领取的跨阶段奖励
            JsonArray boxNumRecordArray = unionBoxInfo.getBoxNumRecordArray();
            for (int i = 0; i < boxNumRecordArray.size(); i++) {
                if (i % 2 == 0) {
                    int boxId = boxNumRecordArray.getInteger(i);
                    int oldNum = boxNumRecordArray.getInteger(i + 1);
                    if (receiveBoxNum >= oldNum){
                        continue;
                    }
                    int receiveNum = oldNum - receiveBoxNum;
                    UnionManager.getUnionBoxRewardByNun(boxId, receiveNum, takeRewardList);
                    receiveBoxNum = oldNum;
                }
            }
            userUnionBox.putReceiveBoxId(unionBoxInfo.getBoxId());
        }

        int receiveNum = totalNum - receiveBoxNum;
        UnionManager.getUnionBoxRewardByNun(unionBoxInfo.getBoxId(), receiveNum, takeRewardList);
        userUnionBox.putReceiveBoxNum(totalNum);
        userUnionBox.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionBox);
        if (!takeRewardList.isEmpty()) {
            RewardManager.addReward(userInfo, takeRewardList, pbUserData, LogType.UNION_DISPOSABLE_BOX_PROGRESS_REWARD);
        }
        return response;
    }

    // CMD_GAME_UNION_DECORATION_MAIN_INFO = 72944; // 地标装饰界面信息 [1]第一次请求
    public static Object CMD_GAME_UNION_DECORATION_MAIN_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionDecorationMainInfoRequest request = CSGameUnionDecorationMainInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionDecorationMainInfoResponse.Builder response = CSGameUnionDecorationMainInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<UnionUnlockDecoration> unionUnlockDecorationList = UnionManager.getUnionUnlockDecorationList(unionId);
        for (UnionUnlockDecoration unionUnlockDecoration : unionUnlockDecorationList) {
            pbUserData.getUnionBuilder().putUnlockDecorationList(unionUnlockDecoration.getId(), true);
            pbUserData.getUnionBuilder().putUnlockDecorationLevelList(unionUnlockDecoration.getId(), unionUnlockDecoration.getLevel());  // 存放等级信息
        }
        return response;
    }
    // CMD_GAME_UNION_DECORATION_ACTIVATE = 72945; // 地标装饰激活
    public static Object CMD_GAME_UNION_DECORATION_ACTIVATE(RequestParam clientParam) throws Exception {
        CSGameUnionDecorationActivateRequest request = CSGameUnionDecorationActivateRequest.parseFrom(clientParam.getData());
        CSGameUnionDecorationActivateResponse.Builder response = CSGameUnionDecorationActivateResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        int decorationId = request.getDecorationId();
        if (unionInfo.getDecorationId() == decorationId) {
            return ErrorWord.NOT_DATA_4;
        }
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionDecorationLock(unionId));

            UnionDecoration decoration = UnionManager.getUnionDecoration(decorationId);
            if (decoration == null) {
                return ErrorWord.NOT_DATA_5;
            }

            // 已激活
            List<UnionUnlockDecoration> unionUnlockDecorationList = UnionManager.getUnionUnlockDecorationList(unionId);
            if (unionUnlockDecorationList.stream().anyMatch(x -> x.getId() == decorationId)) {
                return ErrorWord.NOT_DATA_6;
            }

            // 技能上限
//            if (AllParam.UNION_DECORATION_ADD_SKILL_IDS.length < unionUnlockDecorationList.size() + 1) {
//                return ErrorWord.NOT_DATA_7;
//            }

            Common.PBUserData.Builder pbUserData = response.getUserBuilder();
            // 判断是否是解锁首个地标建筑，第一个不需要消耗
            if (unionUnlockDecorationList.isEmpty()){
                unionInfo.putDecorationId(decorationId);
                unionInfo.update();
                ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
            }else{
                int costNum = decoration.getNeed();
                if (unionInfo.getContribution() < costNum) {
                    return ErrorWord.NOT_DATA_8;
                }
                // 执行逻辑
                var oldContribution = unionInfo.getContribution();
                unionInfo.addContribution(-costNum);//  扣除联盟币
                // 记录消耗日志
                MotuLogManager.logItemIncome(userInfo, ItemId.TYPE_UNION_CONTRIBUTION, ItemId.TYPE_UNION_CONTRIBUTION, oldContribution, costNum, LogType.UNION_RECIPROCITY_ACTIVATE);// 记录获得日志
                // 激活成功并使用(策划说先不使用)
                // unionInfo.putDecorationId(decorationId);
                unionInfo.update();
                ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
            }

            // 新增解锁记录
            UnionUnlockDecoration unionUnlockDecoration = new UnionUnlockDecoration(unionId, userId, decorationId);
            unionUnlockDecoration.putLevel(1);
            unionUnlockDecoration.insert();
            pbUserData.getUnionBuilder().putUnlockDecorationList(unionUnlockDecoration.getId(), true);
            pbUserData.getUnionBuilder().putUnlockDecorationLevelList(unionUnlockDecoration.getId(), unionUnlockDecoration.getLevel());

            //        int activeNum = unionUnlockDecorationList.size() + 1;
            //        int skillId = AllParam.UNION_DECORATION_ADD_SKILL_IDS[activeNum - 1];
//            int skillId = AllParam.UNION_DECORATION_ADD_SKILL_IDS[unionUnlockDecorationList.size()]; // 位置刚好是上个激活数
//            Skill skill = SkillManager.getSkill(skillId);
            // 更新自己的就可以了
            boolean isChange = UnionManager.addPartnerSkillAddBySkillNew(userId, pbUserData, decoration, unionUnlockDecoration);   // 固定值加成
            boolean isChange2 = UnionManager.addPartnerSkillAddBySkillNewPer(userId, unionId,pbUserData);   // 总等级百分比加成
            if (isChange2 || isChange){
                BoardcastManager.publicUnionSyncUserPower(userInfo, unionId);// 广播给联盟其他成员 同步战力和城市收益，联盟建筑对城市收益有加成，联盟地标对战力有加成
            }
        } catch (InvalidProtocolBufferException e) {
            return ErrorWord.PROTOCOL_PARSE_FAILED;
        } finally {
            MainService.releaseVertLock(lock);
        }
        return response;
    }
    // CMD_GAME_UNION_DECORATION_USE = 72946; // 地标装饰使用
    public static Object CMD_GAME_UNION_DECORATION_USE(RequestParam clientParam) throws Exception {
        CSGameUnionDecorationUseRequest request = CSGameUnionDecorationUseRequest.parseFrom(clientParam.getData());
        CSGameUnionDecorationUseResponse.Builder response = CSGameUnionDecorationUseResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        int decorationId = request.getDecorationId();
        // 重复使用
        List<UnionUnlockDecoration> unionUnlockDecorationList = UnionManager.getUnionUnlockDecorationList(unionId);
        if (unionUnlockDecorationList.stream().noneMatch(x -> x.getId() == decorationId)) {
            return ErrorWord.NOT_DATA_4;
        }

        if (unionInfo.getDecorationId() == decorationId) {
            return ErrorWord.NOT_DATA_5;
        }

        unionInfo.putDecorationId(decorationId);
        unionInfo.update();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        return response;
    }

    // CMD_GAME_UNION_DECORATION_LEVEL_UP = 72951; // 地标装饰升级
    public static Object CMD_GAME_UNION_DECORATION_LEVEL_UP(RequestParam clientParam) throws Exception {
        CSGameUnionDecorationLevelUpRequest request = CSGameUnionDecorationLevelUpRequest.parseFrom(clientParam.getData());
        CSGameUnionDecorationLevelUpResponse.Builder response = CSGameUnionDecorationLevelUpResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        int decorationId = request.getDecorationId();
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionDecorationLock(unionId));

            UnionDecoration decoration = UnionManager.getUnionDecoration(decorationId);
            if (decoration == null) {
                return ErrorWord.NOT_DATA_5;
            }

            // 已激活
            UnionUnlockDecoration unionUnlockDecoration = UnionManager.getUnionUnlockDecorationById(unionId,decorationId);
            if (unionUnlockDecoration == null) {
                return ErrorWord.NOT_DATA_6;
            }

            Common.PBUserData.Builder pbUserData = response.getUserBuilder();
            Skill skill = SkillManager.getSkill(decoration.getSkill());
            if (skill == null) {
                return ErrorWord.NOT_DATA_1;
            }
            int curLevel = unionUnlockDecoration.getLevel();
            int newLevel = curLevel + 1;
            if (skill.getMaxLevel() > 0 && newLevel > skill.getMaxLevel()) {
                return ErrorWord.ALREADY_MAX;//  已达到最大等级
            }

            List<RewardItem> rewardItems = skill.takeLevelUpItems(curLevel);// 消耗的道具数量
            if (!BagManager.checkNeedItemNum(userInfo, rewardItems)) {
                return ErrorWord.ITEM_LACK;// 道具不足
            }
            // 执行逻辑
            if (!rewardItems.isEmpty()){
                long costNum = rewardItems.getFirst().getItemNum();
                int oldContribution = unionInfo.getContribution();
                unionInfo.addContribution((int)-costNum);//  扣除联盟币
                MotuLogManager.logItemIncome(userInfo, ItemId.TYPE_UNION_CONTRIBUTION, ItemId.TYPE_UNION_CONTRIBUTION, oldContribution, costNum, LogType.UNION_RECIPROCITY_ACTIVATE);// 记录获得日志
                unionInfo.update();
                ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
            }

            unionUnlockDecoration.putLevel(newLevel);
            unionUnlockDecoration.update();
            pbUserData.getUnionBuilder().putUnlockDecorationLevelList(unionUnlockDecoration.getId(), unionUnlockDecoration.getLevel());

            // 更新联盟的所有成员的技能加成
            boolean isChange = UnionManager.addPartnerSkillAddBySkillNew(userId, pbUserData, decoration, unionUnlockDecoration);   // 固定值加成
            boolean isChange2 = UnionManager.addPartnerSkillAddBySkillNewPer(userId, unionId,pbUserData);   // 总等级百分比加成
            if (isChange2 || isChange){
                BoardcastManager.publicUnionSyncUserPower(userInfo, unionId);// 广播给联盟其他成员 同步战力和城市收益，联盟建筑对城市收益有加成，联盟地标对战力有加成
            }
        } catch (InvalidProtocolBufferException e) {
            return ErrorWord.PROTOCOL_PARSE_FAILED;
        } finally {
            MainService.releaseVertLock(lock);
        }
        return response;
    }

    // CMD_GAME_UNION_RECIPROCITY_MAIN_INFO = 72947; // 联盟互助界面信息 [2]每次打开请求
    public static Object CMD_GAME_UNION_RECIPROCITY_MAIN_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionReciprocityMainInfoRequest request = CSGameUnionReciprocityMainInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionReciprocityMainInfoResponse.Builder response = CSGameUnionReciprocityMainInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }

        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnionReciprocity userUnionReciprocity = UnionManager.getUserUnionReciprocity(userId);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionReciprocity, true);
        List<UserUnionReciprocityRecord> records = UnionManager.getUserUnionReciprocityRecordList(userId);// 帮助记录

        List<UnionReciprocityList> allUnionReciprocityList = UnionManager.getUnionReciprocityList(unionId);
        for (UnionReciprocityList unionReciprocityList : allUnionReciprocityList) {
            boolean isHelp = unionReciprocityList.isCanHelp(userId, records, unionInfo);// 是否可以进行帮助
            pbUserData.getUnionBuilder().getUnionReciprocityInfoBuilder().putReciprocityList(unionReciprocityList.getId(),  UnionManager.takePBUnionReciprocityListInitBuilder(isHelp, unionReciprocityList).build());
        }

        return response;
    }
    // CMD_GAME_UNION_RECIPROCITY_HELP = 72948; // 联盟互助帮助，给玩家助力
    public static Object CMD_GAME_UNION_RECIPROCITY_HELP(RequestParam clientParam) throws Exception {
        CSGameUnionReciprocityHelpRequest request = CSGameUnionReciprocityHelpRequest.parseFrom(clientParam.getData());
        CSGameUnionReciprocityHelpResponse.Builder response = CSGameUnionReciprocityHelpResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.NOT_DATA_2;
        }

        List<UserUnionReciprocityRecord> records = UnionManager.getUserUnionReciprocityRecordList(userId);// 帮助记录
        boolean isOneKey = request.getType() == 1 ? true : false;// 是否一键互助所有
        List<UnionReciprocityList> list = new ArrayList<>();// 需要处理的求助信息列表
        if (isOneKey) {
            int count = 0;
            for (UnionReciprocityList unionReciprocityList : UnionManager.getUnionReciprocityList(unionId)) {
                if (unionReciprocityList.isCanHelp(userId, records, unionInfo)) {
                    list.add(unionReciprocityList);
                    count++;
                }
                if (count >= AllParam.UNION_RECIPROCITY_ONE_KEY_HELP_MAX) {
                    break;// 最多对互助99次
                }
            }
        } else {
            UnionReciprocityList unionReciprocityList = UnionManager.getUnionReciprocity(unionId, request.getHelpId());
            if (unionReciprocityList.isCanHelp(userId, records, unionInfo)) {
                list.add(unionReciprocityList);
            }
        }

        if (list.size() == 0) {
            return ErrorWord.NOT_DATA;// 没有可以互助的信息
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnionReciprocity userUnionReciprocity = UnionManager.getUserUnionReciprocity(userId);
        int dayGetUnionCoin = userUnionReciprocity.getDayGetUnionCoin();
        int maxItemNum = AllParam.UNION_RECIPROCITY_DAY_GET_UNION_COIN_MAX - dayGetUnionCoin;// 本次可以获得联盟币上限
        int itemNum = Math.min(maxItemNum, list.size() * AllParam.UNION_RECIPROCITY_HELP_REWARD);
        if (itemNum > 0) {
            RewardManager.addReward(userInfo, ItemId.TYPE_UNION_COIN, itemNum, pbUserData, LogType.UNION_RECIPROCITY_REWARD);// 获得联盟币

            userUnionReciprocity.addDayGetUnionCoin(itemNum);
            userUnionReciprocity.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userUnionReciprocity);
        }

        for (UnionReciprocityList unionReciprocityList : list) {
            UnionManager.handleDoHelp(pbUserData, userInfo, unionInfo, unionReciprocityList);// 对联盟互助请求，进行帮助
            unionReciprocityList.update();
            boolean isCanHelp = false;// 已经帮助过了。告诉客户端不能再次帮助。按钮变灰
            pbUserData.getUnionBuilder().getUnionReciprocityInfoBuilder().putReciprocityList(unionReciprocityList.getId(),  UnionManager.takePBUnionReciprocityListBuilder(isCanHelp, unionReciprocityList.getHelpNum()).build());

            UnionManager.addUserUnionReciprocityRecord(userId, unionReciprocityList);// 生成帮助记录
        }

        ThinkingDataManager.pushUserUnionHelpEvent(userInfo, list.size());// 数数上报数据

        return response;
    }

    //   CMD_GAME_UNION_RECIPROCITY_SEEK_HELP = 72949; // 联盟互助求助 发起求助
    public static Object CMD_GAME_UNION_RECIPROCITY_SEEK_HELP(RequestParam clientParam) throws Exception {
        CSGameUnionReciprocitySeekHelpRequest request = CSGameUnionReciprocitySeekHelpRequest.parseFrom(clientParam.getData());
        CSGameUnionReciprocitySeekHelpResponse.Builder response = CSGameUnionReciprocitySeekHelpResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.NOT_DATA_2;
        }

        // 校验type
        int type = request.getType();
        long seekHelpId = request.getSeekId();// 队伍id
        if (type != UnionConstant.UNION_RECIPROCITY_TYPE_1 && type != UnionConstant.UNION_RECIPROCITY_TYPE_2 && type != UnionConstant.UNION_RECIPROCITY_TYPE_3) {
            return ErrorWord.BAD_PARAM;
        }

        // 校验重复求助
        PBUserData.Builder pbUserData = response.getUserBuilder();
        boolean flag = true;// 是否可以发起求助
        String uniqeId = "";//唯一值id
        UserWorldTeam userWorldTeam = null;
        UserSoldierRecover userSoldierRecover = null;
        switch (type) { // 校验是否可以帮助
            case UnionConstant.UNION_RECIPROCITY_TYPE_1 :
            case UnionConstant.UNION_RECIPROCITY_TYPE_2 : {
                userWorldTeam = WorldManager.getUserWorldTeam(userId, (int)seekHelpId);
                uniqeId = userWorldTeam.getUniqeId();
                flag = WorldManager.isCanHelpWorldTeam(userWorldTeam);
                break;
            }
            case UnionConstant.UNION_RECIPROCITY_TYPE_3 : {
                userSoldierRecover = BuildManager.getUserSoldierRecover(userId);
                uniqeId = userSoldierRecover.getUniqeId();
                flag = BuildManager.isCanSeekHelpSoldierRecover(userSoldierRecover);
                break;
            }
        }
        if (!flag) {
            return ErrorWord.REPEATED_OPERATION;// 该事件已经发起求助过了
        }

        UnionReciprocityList unionReciprocityList = UnionManager.createUnionReciprocityList(unionInfo, userId, type, seekHelpId, uniqeId);
        if (type == UnionConstant.UNION_RECIPROCITY_TYPE_1 || type == UnionConstant.UNION_RECIPROCITY_TYPE_2) {
            userWorldTeam.putHelpDbid(unionReciprocityList.getId());
            userWorldTeam.update();
        }
        if (type == UnionConstant.UNION_RECIPROCITY_TYPE_3) {
            userSoldierRecover.putHelpDbid(unionReciprocityList.getId());
            userSoldierRecover.update();
        }

        pbUserData.getUnionBuilder().getUnionReciprocityInfoBuilder().putReciprocityList(unionReciprocityList.getId(),  UnionManager.takePBUnionReciprocityListInitBuilder(false, unionReciprocityList).build());
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_71, 1);// 发起联盟互助{0}次

        // 通知联盟的其他玩家
        BoardcastManager.publicUnionHelp(userInfo, unionId, unionReciprocityList);
        return response;
    }

// CMD_GAME_UNION_CHANGE_DES = 72950; // 联盟改宣言
    public static Object CMD_GAME_UNION_CHANGE_DES(RequestParam clientParam) throws Exception {
        CSGameUnionChangeDesRequest request = CSGameUnionChangeDesRequest.parseFrom(clientParam.getData());
        CSGameUnionChangeDesResponse.Builder response = CSGameUnionChangeDesResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return ErrorWord.NOT_DATA_10;
        }
        // 功能未开启
        if (!SystemManager.checkModuleOpen(userInfo,SystemConstant.SYSTEM_MODULE_ID_UNION)) {
            return ErrorWord.MODULE_LOCKED;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA_1;
        }
        // 权限不足
        if (!userUnion.IsPostDeputy()) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        // 没有该联盟
        if (unionInfo == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        //宣言检验
        String newDes = request.getDes();
        // 过滤敏感字符
        try {
            newDes = SensitivewordEngine.replaceWordBySdk(newDes, userExtInfo.getPlatform());
        } catch (Exception e) {
            return ErrorWord.BAD_WORD;
        }

        if (newDes.length() > AllParam.UNION_DES_MAX) {
            newDes = newDes.substring(0, AllParam.UNION_DES_MAX);
        }
        unionInfo.putDes(newDes);
        unionInfo.update();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, unionInfo);
        return response;
    }


    // CMD_GAME_UNION_INVITE = 72952; // 邀请对方加入联盟
    public static Object CMD_GAME_UNION_INVITE(RequestParam clientParam) throws Exception {
        CSGameUnionInviteRequest request = CSGameUnionInviteRequest.parseFrom(clientParam.getData());
        CSGameUnionInviteResponse.Builder response = CSGameUnionInviteResponse.newBuilder();
        long userId = clientParam.getUserId();

        long buddyId = request.getBuddyId();// 好友id

        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (!ChatManager.isCanChat(userInfo, userExtInfo)) {
            return ErrorWord.WRONG_STATUS;// 被禁言或是太频繁发言
        }

        //判断是否是好友
        UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, buddyId);
        if (userBuddy == null) {
            return ErrorWord.ENTITY_NOT_EXIST;//  不是好友
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion == null || userUnion.getUnionId() == 0) {
            return ErrorWord.NOT_DATA;// 我尚未加入联盟
        }

        UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
        if (unionInfo == null) {
            return ErrorWord.NOT_DATA;// 我尚未加入联盟
        }

        int subType = ChatManager.CHAT_SUB_TYPE_COMMON;// 普通聊天
        // 执行逻辑
        int msgId = MailConstant.UNION_INVITE_CONTENT;
        String msg = ChatManager.getSystemMsg(msgId, unionInfo.getName());

        JsonObject jsonObject = new JsonObject();
        JsonArray link = new JsonArray();
        JsonObject tmp = new JsonObject();
        tmp.put("linkType", 10211);
        JsonArray jsonArray2 = new JsonArray().add(unionInfo.getId());
        tmp.put("values", jsonArray2.toString());

        link.add(tmp);
        jsonObject.put("link", link);

        ChatBuddy chatBuddy = new ChatBuddy(userInfo, subType, buddyId, msg, jsonObject.toString());
        chatBuddy.doCreate();

        Common.PBChatMsg.Builder chatMsgBuilder = chatBuddy.takeBuilder();
        // 推送给好友
        GameUser.pushToUser(buddyId, ChatManager.takeResponseData(chatMsgBuilder));
        response.setChatMsg(chatMsgBuilder);
        response.setBuddyId(buddyId);

        return response;
    }
}


